[英]How to find the most similar word in a list in python
我有一个单词列表
list = ['car', 'animal', 'house', 'animation']
我想将每个列表项与字符串str1
进行比较,输出应该是最相似的单词。 示例:如果str1
是anlmal
则animal
是最相似的词。 我怎么能在python中做到这一点? 通常,我的列表中的单词可以很好地相互区分。
我检查了 difflib.get_close_matches(),但它对我不起作用。 我在这里写了一个强大的解决方案,用作:
最近匹配,最近匹配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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.