2012-04-04 139 views
3

我想比較兩個具有表示相同對象的自由文本的數據列表。示例Python字符串比較相似性

List 1 ['abc LLC','xyz, LLC'] 
List 2 ['abc , LLC','xyz LLC'] 

這是一個簡單的例子,但問題是可能會有許多更改,例如更改大小寫或添加一些「。」。在之間。是否有任何python包可以做比較並給出相似度量度?

+0

你是什麼意思的「概率」? – 2012-04-04 07:50:59

+0

@OliCharlesworth我認爲作者想要找到兩個字符串之間的相似百分比。就好像這些字符串有85%的相似。 – bezmax 2012-04-04 07:52:28

+0

你不想要「可能性」,你想要「相似性」。 http://stackoverflow.com/questions/682367/good-python-modules-for-fuzzy-string-comparison – Joe 2012-04-04 07:52:39

回答

7

對於非精確字符串匹配,您可以使用Levenshtein Distance算法的實現,例如this one from Wikibooks

另一種選擇是,例如,一切爲小寫原料比較之前摺疊,刪除空格,等等 - 這當然取決於你的使用情況:

import string, unicodedata 
allowed = string.letters + string.digits 
def fold(s): 
    s = unicodedata.normalize("NFKD", unicode(s).lower()).encode("ascii", "ignore") 
    s = "".join(c for c in s if c in allowed) 
    return s 

for example in ['abc LLC','xyz, LLC', 'abc , LLC','xyz LLC']: 
    print "%r -> %r" % (example, fold(example)) 

將打印

'abc LLC' -> 'abcllc' 
'xyz, LLC' -> 'xyzllc' 
'abc , LLC' -> 'abcllc' 
'xyz LLC' -> 'xyzllc'