2013-05-29 49 views
0

我想比較一個字符串與其他字符串的列表並獲得最相似的結果。我可以用python中的difflib來完成它。但是,我想要做的是獲得列表中的訂單。如何在Python中最相似的字符串列表中獲取訂單

from difflib import get_close_matches 

a = ['abcde', 'efghij', 'klmno'] 
b = 'cdefgh' 
print get_close_matches(b, a) 

該代碼將返回['efghij']這是正確的。但是,如果我想要得到1,會怎麼樣?因爲a[1] = 'efghij'

和,我該如何獲得相似比? 我應該再次用SequenceMatcher(None, b, a).ratio()來計算嗎?

回答

0

這給你的第一次出現:

>>> ['abcde', 'efghij', 'klmno'].index('efghij') 
1 
0

米凱什答案是正確的,但是如果速度是必要的,你需要很多的查找,那麼我會建議你使用的字典:

a_hash = dict(zip(a, range(len(a)))) 
a_hash['efghij'] # prints 1 

我從來沒有使用difflib,但我的猜測是你會做以下事情:

import difflib 
difflib.SequenceMatcher(None, b, a[1]).ratio() 
# or 
difflib.SequenceMatcher(None, b, a_hash[difflib.get_close_matches(b, a)]).ratio() 
# both returns 0.66666 
# presumably because both strings have de and 2/6 = 0.666 

那是wha你想要嗎?

相關問題