在非索引文本文件中搜索单词的最快方法 - Python

时间:2013-07-08 07:11:56

标签: python text-search search

考虑一个150万行的文本文件,每行大约50-100个单词。

要查找包含该字词的行,使用os.popen('grep -w word infile')似乎比

更快
for line in infile: 
  if word in line:
    print line

如何在python中的文本文件中搜索单词?搜索大型unindex文本文件的最快方法是什么?

2 个答案:

答案 0 :(得分:2)

有几种快速搜索算法(参见wikipedia)。它们要求您将单词编译成某种结构。 Grep正在使用Aho-Corasick algorithm

我没有看到python的in的源代码,但是

    为每一行编译
  1. word需要时间(我怀疑in编译任何内容,显然它可以编译它,缓存结果等),或
  2. 搜索效率低下。考虑在“worword”中搜索“word”,首先检查“worw”并失败,然后检查“o”,然后检查“r”并失败,等等。但是没有理由重新检查“o”或“r”你很聪明。例如,Knuth–Morris–Pratt algorithm根据搜索到的单词创建一个表,告诉它在发生故障时可以跳过多少个字符。

答案 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'))