假设我有一个 string
"Hello"
和一个列表
words = ['hello', 'Hallo', 'hi', 'house', 'key', 'screen', 'hallo','question', 'Hallo', 'format']
如何找到最接近 "Hello"
并出现在列表 words
中的 n 个单词
?
在这种情况下,我们将有 ['hello', 'hallo', 'Hallo', 'hi', 'format'...]
所以策略是从最近的单词到最远的单词对列表单词进行排序。
我想过这样的事情
word = 'Hello'
for i, item in enumerate(words):
if lower(item) > lower(word):
...
但在大型列表中非常慢。
更新
difflib
可以工作,但也很慢。 (words list
里面有 630000+ 个单词(已排序,每行一个))。因此,每次搜索最接近的单词时,检查列表需要 5 到 7 秒!
最佳答案
使用 difflib.get_close_matches
.
>>> words = ['hello', 'Hallo', 'hi', 'house', 'key', 'screen', 'hallo', 'question', 'format']
>>> difflib.get_close_matches('Hello', words)
['hello', 'Hallo', 'hallo']
请查看文档,因为该函数默认返回 3 个或更少的最接近的匹配项。
关于Python:找到最接近的字符串(从列表中)到另一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10018679/