簡體   English   中英

如何在python的列表中找到最相似的單詞

[英]How to find the most similar word in a list in python

我有一個單詞列表

list = ['car', 'animal', 'house', 'animation']

我想將每個列表項與字符串str1進行比較,輸出應該是最相似的單詞。 示例:如果str1anlmalanimal是最相似的詞。 我怎么能在python中做到這一點? 通常,我的列表中的單詞可以很好地相互區分。

使用difflib

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

正如您從閱讀源中看到的那樣,“接近”匹配按從最好到最差的順序排列。

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

我檢查了 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM