考虑一个150万行的文本文件,每行大约50-100个单词。
要查找包含该字词的行,使用os.popen('grep -w word infile')
似乎比
for line in infile:
if word in line:
print line
如何在python中的文本文件中搜索单词?搜索大型unindex文本文件的最快方法是什么?
答案 0 :(得分:2)
有几种快速搜索算法(参见wikipedia)。它们要求您将单词编译成某种结构。 Grep正在使用Aho-Corasick algorithm。
我没有看到python的in
的源代码,但是
word
需要时间(我怀疑in
编译任何内容,显然它可以编译它,缓存结果等),或答案 1 :(得分:1)
我可能会建议您安装并使用the_silver_searcher。
在我的测试中,搜索了大约2900行的1GB文本文件,并且在00h 00m 00.73s内发现了数百个搜索到的单词条目,即不到一秒!
这是Python 3代码,它使用它来搜索单词并计算找到它的次数:
import subprocess
word = "some"
file = "/path/to/some/file.txt"
command = ["/usr/local/bin/ag", "-wc", word, file]
output = subprocess.Popen(command, stdout=subprocess.PIPE).stdout.read()
print("Found entries:", output.rstrip().decode('ascii'))
此版本搜索单词并打印行号+实际文本是找到的单词:
import subprocess
word = "some"
file = "/path/to/some/file.txt"
command = ["/usr/local/bin/ag", "-w", word, file]
output = subprocess.Popen(command, stdout=subprocess.PIPE)
for line in output.stdout.readlines():
print(line.rstrip().decode('ascii'))