簡體   English   中英

用多行中的條件替換行的變化

[英]Replace change of line with condition in multiple lines

我有一個文本文件,如下所示:

3/11/21, 6:13 PM - Gil: X1000
3/11/21, 6:15 PM - Sergio: <Media omitted>
3/11/21, 6:19 PM - Sergio: X400
3/11/21, 6:20 PM - Sergio: Los amigos de vonzo en Francia:

1. La Tóxica
2. El brujo vodoo
3. El/La Zoofilic@
3/11/21, 6:20 PM - Sergio: :V
3/11/21, 6:21 PM - Joan :V: JAJAJAJAJA

大多數行都以很容易用正則表達式捕獲的日期/時間開頭。

當找不到日期/時間時,我想刪除行的更改,我希望類似(在新文件中):

3/11/21, 6:13 PM - Gil: X1000
3/11/21, 6:15 PM - Sergio: <Media omitted>
3/11/21, 6:19 PM - Sergio: X400
3/11/21, 6:20 PM - Sergio: Los amigos de vonzo en Francia: 1. La Tóxica 2. El brujo vodoo 3. El/La Zoofilic@
3/11/21, 6:20 PM - Sergio: :V
3/11/21, 6:21 PM - Joan :V: JAJAJAJAJA

我遇到的問題是我正在讀取文件:

        input = open(self.fileName, encoding="utf8" , errors='replace')
        for line in input:
            output.write(re.sub(#SOMETHING))

有了這個,我當時只能讀取一行,我真的不知道如何用n+1行中的條件更改n行。

如何更改行更改第n行與第n+1行中的條件?

只有在有日期時間時才寫\n

import re

datetime_pattern = '\d{1,2}/\d{1,2}/\d{1,2},\s\d{1,2}:\d{1,2}\s[AP]M'

for line in input:
    have_datetime = bool(re.match(datetime_pattern, line)
    if have_datetime:
        output.write('\n')
    output.write(line.strip('\n'))

with語句是在 Python 中讀/寫文件的推薦方式。 然后我們可以讀取每一行,將其與所需的模式匹配並相應地添加換行符。

import re

datetime_pattern = '\d{1,2}/\d{1,2}/\d{1,2},\s\d{1,2}:\d{1,2}\s[AP]M'
with open(input_file_path, 'r') as infile:
    with open(output_file_path, 'w') as outfile:
        for (line_number, line) in enumerate(infile):
            # We don't need a newline character at the first line
            if line_number > 0 and re.match(datetime_pattern, line):
                outfile.write('\n')
            outfile.write(line.strip('\n'))



            
import re

with open("text_file.txt", "r") as f:
    lines = f.readlines()

with open("stack_overflow.txt", "w") as f:
    for line in lines:
        if re.findall(r'\d{1,2}/\d{2}/\d{2}', line):
            f.write(line)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM