亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

搜索字符串并刪除包含字符串和下面的行的行

搜索字符串并刪除包含字符串和下面的行的行

瀟瀟雨雨 2021-04-01 21:09:03
我有一個文本文件,其中包含### 174.10.150.10 on 2018-06-20 12:19:47.533613 ###IP : 174.10.150.10 : IP : ALL :我目前有使用Regex搜索日期/時間字符串的代碼。如何刪除包含找到的字符串的行?我要刪除該行以及下面的行。因此,這兩行都將被刪除:### 174.10.150.10 on 2018-06-20 12:19:47.533613 ###IP : 174.10.150.10 : 我的代碼當前僅將“ None”添加到文本文件的底部。import redef run():      try:        with open('file.txt', 'r') as f:            with open('file.txt', 'a') as f2:                reg = re.compile('###\s+\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}.+(\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}.\d{0,})\s###')                for line in f:                    m = reg.match(line)                answer = raw_input("Delete line? ")                if answer == "y":                    # delete line that contains "###" and line underneath                    f2.write(str(m))                else:                    print("You chose no.")    except OSError as e:        print (e)run()
查看完整描述

3 回答

?
守候你守候我

TA貢獻1802條經驗 獲得超10個贊

經過一些基本的重構,結果如下...


import re

valid_lines = []


def run():  

    try:

        with open('file.txt', 'r') as f:

            reg = re.compile('###\s+\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}.+(\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}.\d{0,})\s###\s?')

            lines = f.readlines()

            invalid_index = -10


            for a in range(len(lines)):

                reg_result = reg.match(lines[a])


                if invalid_index == (a - 1):

                    # Skip the line underneath the invalid line

                    continue


                if reg_result != None:

                    # If the line matches the regexp.

                    invalid_index = a

                    answer = raw_input("Delete line? ")


                    if answer.lower() != 'y':

                        print("You chose no.")

                        valid_lines.append(lines[a])

                else:

                    valid_lines.append(lines[a])


        with open('file.txt', 'w') as f:

            # Override the file...

            f.writelines(valid_lines)


    except OSError as e:

        print (e)


run()

如果您要刪除任何以###then開頭的行,也許您應該將其視為regexp:###.*


編輯:在您的正則表達式中,您應該\s?在末尾添加a以可選地匹配\n,因為文件包含換行符。另外,請使用fullmatch()代替match()。


查看完整回答
反對 回復 2021-04-09
  • 3 回答
  • 0 關注
  • 165 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號