Python-在非常大的文本文件(8GB)中查找数据的最佳方式



我想扫描8GB的文本文件(它是一个日志文件(来查找特定的单词。这些字存储在超过3400行的数据帧中。

我尝试了下面的解决方案,它避免了必须加载整个文档:

with open(filename) as f:
for line in f:
do_stuff(line)

然而,这需要很长时间来处理。扫描整个文档一个单词需要2分钟以上的时间。将其与3400相乘需要113个小时才能完成脚本。

有什么办法可以改进这个过程吗?

创建单词的集合words = set(column_of_words)

然后做一些类似的事情:

with open(filename) as f:
for line in f:
words_in_line = set(line.split())
matches = words & words_in_line #the intersection
if len(matches) > 0:
#do something with the matches

无论你做什么,都不要扫描同一个文件3400次。想办法只扫描一次。

最新更新