Python:找到最接近的字符串(从列表中)到另一个字符串

标签 python string algorithm list

假设我有一个 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/

相关文章:

python - 在 Python 中加载 JSON 文件抛出错误。

Python 多处理错误 : AttributeError: module '__main__' has no attribute '__spec__'

java - 如何转换 int 以返回字符串,这就是我们所说的 int

c - 字符串操作复制字符串的部分c编程

C++字符串库错误: string subscript out of range

java - Java中给定的long类型的正数的所有数字的总和

c - C 中的数组排序函数

python - 使用机器学习算法从python中的两个列表中找到最短点

python - 在 Pandas 中返回没有时间的日子

algorithm - 最适合多条线的交集