我有一个拥有大量行(0.5-1.5百万)的文件,每一行都是一个文件名(长度约为50-100个字符)。我需要一个能快速搜索给定查询条件的程序。现在我的代码看起来像这样:
def similarity(haystack, needle):
words = re.findall(r'\w+', haystack.lower()) # replacing by split with separators reduces time by about 4 seconds
for word in words:
if word == needle:
return 10
for word in words:
if word.startswith(needle):
return 10 ** (len(needle) / len(word))
if needle in haystack:
return 1
return 0
def search(text):
text = text.lower()
lines = [(similarity(x, text), x) for x in lines]
return [x[1] for x in sorted(lines, reverse = True)[:15]]
在我的电脑上,示例文件在大约15秒内运行完毕(几乎所有时间都花费在
similarity()
函数中),但我希望它能够在几秒钟内几乎立刻完成。如何实现这一点?我认为索引可能有所帮助,但对其可能的结构一无所知。而且,如果可能的话,我希望搜索变得“更模糊”——例如,使用N-gram或类似的东西。但现在主要关注的是速度。
更新:
同样的
lines
会被多次搜索。
needle
始终只是一个单词。“更模糊”意味着即使
needle
略微输入错误,也应该能够找到相应的行。