[英]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.