【问题标题】:How to return the most similar word from a list of words? [closed]如何从单词列表中返回最相似的单词? [关闭]
【发布时间】:2014-07-06 16:22:03
【问题描述】:

如何创建一个函数,从单词列表中返回最相似的单词,即使单词并不完全相同?

该函数应该有两个输入:一个用于单词,另一个用于列表。该函数应返回与该单词最相似的单词。

lst = ['apple','app','banana store','pear','beer']

func('apple inc.',lst)
>>'apple'
func('banana',lst)
>>'banana store'

通过一些研究,我似乎必须使用模糊字符串匹配、NLTK 和 Levenshtein-distance 的概念,在创建这样的函数时我很难实现这些概念。

我还应该指出,我所说的相似,只是指字符,我根本不关心这个词的含义。

【问题讨论】:

  • 你应该有一些具体的启发式方法。目前,这个问题太宽泛了。
  • 这真的取决于你所说的“相似”是什么意思。考虑Bird这个词。 Crow 和Bard 中的哪个词与Bird 更相似?根据您的答案,您的方法会有所不同。
  • 感谢您的提问。相似,我指的只是字符上的相似,而不是词义上的相似。因此,在我的用例中,Bird 与 Bard 相比与 Crow 更相似。
  • python的标准库中没有difflib吗?

标签: python regex list nltk levenshtein-distance


【解决方案1】:

调试慢的解决办法:

def func(word, lst):
  items = sorted((dist(word, w), w) for w in lst)
  # Print items here for debugging.
  if not items: 
    raise ValueError('List of words is empty.')
  return items[0][1]

或者,这更快并且使用更少的内存:

def func(word, lst):
  return min((dist(word, w), w) for w in lst)[1]

请参阅 https://stackoverflow.com/questions/682367/good-python-modules-for-fuzzy-string-comparison 以实现 dist。其中一个答案有一个 Levenshtein-distance 实现的链接。

【讨论】:

  • 谢谢 - 为了清楚起见,只需要导入 Levenshtein 就可以使用它了吗?
  • 必须先安装,然后才能导入。
猜你喜欢
  • 1970-01-01
  • 2015-05-21
  • 2015-06-22
  • 2015-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-16
  • 1970-01-01
相关资源
最近更新 更多