假设我有一个字符串
"Hello"
和一个列表
words = ['hello', 'Hallo', 'hi', 'house', 'key', 'screen', 'hallo','question', 'Hallo', 'format']
如何在列表words
中找到与"Hello"
最接近的n个单词
?
在这种情况下,我们会有['hello','hallo','Hallo','hi','format'...]
因此,策略是将列表words
按从最接近单词到最远的顺序排序。
我考虑了类似以下的代码:
word = 'Hello'
for i, item in enumerate(words):
if lower(item) > lower(word):
...
但是在大型列表中非常缓慢。
更新: difflib
可以使用,但在大型列表中也非常缓慢。(单词列表
内含 630000+ 单词(已排序,每行一个))。因此,对于每个搜索最接近的单词,检查列表需要 5 到 7 秒钟!