如何在Python中查找列表中最相似的单词

29

我有一个单词列表

list = ['car', 'animal', 'house', 'animation']
我希望比较列表中的每个项目与字符串str1,并输出最相似的单词。例如:如果str1anlmal,则animal是最相似的单词。我应该如何在Python中实现?通常,我的列表中的单词互相区分度很高。
2个回答

47

使用difflib:

difflib.get_close_matches(word, ['car', 'animal', 'house', 'animation'])

从查看源代码可以看出,"close"匹配项是按照从好到差的顺序排序的。

>>> import difflib
>>> difflib.get_close_matches('anlmal', ['car', 'animal', 'house', 'animation'])
['animal']

9
如果我有一个大列表,这个操作会耗费很多时间吗?或者这个函数有任何速度优化的方法吗? - Josir

3
我查看了difflib.get_close_matches(),但它对我没有正确地起作用。我在此处编写了一个强大的解决方案,使用方法如下:
closest_match, closest_match_idx = find_closet_match(test_str, list2check)
def find_closet_match(test_str, list2check):
scores = {}
for ii in list2check:
    cnt = 0
    if len(test_str)<=len(ii):
        str1, str2 = test_str, ii
    else:
        str1, str2 = ii, test_str
    for jj in range(len(str1)):
        cnt += 1 if str1[jj]==str2[jj] else 0
    scores[ii] = cnt
scores_values        = numpy.array(list(scores.values()))
closest_match_idx    = numpy.argsort(scores_values, axis=0, kind='quicksort')[-1]
closest_match        = numpy.array(list(scores.keys()))[closest_match_idx]
return closest_match, closest_match_idx

你知道是否可能返回不仅是最接近的,而是前n个,比如前5个吗? - Jorge A. Salazar
我知道这是可能的。 - Hacky
@JorgeA.Salazar,现在一个简单的解决方案是运行函数n次,然后在每次迭代后从list2check中删除closest_match。也可以尝试修改代码。 - amit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接