簡體   English   中英

基於正則表達式/自由文本解析文本文件

[英]Parsing a text file based on regex / free text

我是 python 的新手,所以試圖找到一個關於如何對文本文件執行某些操作的好的解決方案/方法:

我想要實現的目標:
遍歷一個 5k-10k 行的文本文件,找到基於正則表達式和一些自由文本的特定文本,通過逐行檢查,保存並存儲到另一個文件。

在python中實現這一目標的好方法是什么?

讀取文件並解析它的正常方式應該有效嗎?

with open("in.txt") as f:
    lines = [l for l in lines if "ROW" in l]
with open("out.txt", "w") as f1:
    f1.writelines(lines)

其它的辦法

with open("in.txt") as f, open("out.txt", "w") as f1:
    for line in f:
        if "ROW" in line:
            f1.write(line) 

@Ayoub Benayache之上的另一種方法使用re但如果需要,則用於正則表達式模式。

import re

pattern = re.compile(r"^.*pattern.*$", re.M|re.I)

with open("in.txt", 'r') as infile:
    lines = pattern.findall(infile.read())
with open("out.txt", 'w') as outfile:
    outfile.write('\n'.join(lines))

暫無
暫無

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

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