簡體   English   中英

使用Python尋找文件中的特定短語

[英]Looking to find specific phrases in file using Python

我知道論壇上對此有一些非常相似的帖子,但是我需要它來快速掃描文本文件。 我必須通過1 GB的文件運行500張支票,並打印出包含某些短語的行,這是我的代碼:

import re
with open('text.txt', 'r') as f:
    searchstrings = ('aaAa','bBbb')
    for line in f.readlines():
        for word in searchstrings:
            word2 = ".*" + word + ".*"
            match = re.search(word2, line)
            if match:
                print word + "     " + line

我試圖使它返回包含這些短語的任何行,所以即使該行是“ BBjahdAAAAmm”,我也希望它返回,因為其中包含aaaa。 aaAa和bBbb只是示例,列表完全不同。

不要使用f.readlines()您將整個1GB加載到內存中。 一次閱讀一次。

而是:

searchstrings = ('aaAa','bBbb')
with open('text.txt', 'r') as f:
    for line in f:
        for word in searchstrings:
            if word.lower() in line.lower():
               print word + "     " + line

你是說IGNORECASE嗎? 嘗試re.search(word2,line,re.IGNORECASE)。

暫無
暫無

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

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