[英]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.