我正在尝试使用
difflib.get_close_matches
获得最佳匹配的分数:
import difflib
best_match = difflib.get_close_matches(str,str_list,1)[0]
我知道添加“
cutoff
”参数的选项,但不知道如何在设置阈值后获得实际分数。
我错过了什么吗?有没有更好的解决方案来匹配unicode字符串?
我发现 difflib.get_close_matches 是匹配/模糊匹配字符串的最简单方法。但是还有一些其他更高级的库,例如您在评论中提到的 fuzzywuzzy。
但是如果你想使用difflib,你可以使用difflib.SequenceMatcher来获取分数,如下:
import difflib
my_str = 'apple'
str_list = ['ape' , 'fjsdf', 'aerewtg', 'dgyow', 'paepd']
best_match = difflib.get_close_matches(my_str,str_list,1)[0]
score = difflib.SequenceMatcher(None, my_str, best_match).ratio()
在此示例中,“apple”与列表之间的最佳匹配是“ape”,得分为 0.75。
您还可以循环遍历列表并计算所有要检查的分数:
for word in str_list:
print "score for: " + my_str + " vs. " + word + " = " + str(difflib.SequenceMatcher(None, my_str, word).ratio())
对于此示例,您将得到以下内容:
score for: apple vs. ape = 0.75
score for: apple vs. fjsdf = 0.0
score for: apple vs. aerewtg = 0.333333333333
score for: apple vs. dgyow = 0.0
score for: apple vs. paepd = 0.4
difflib 的文档可以在这里找到:https://docs.python.org/2/library/difflib.html
要回答这个问题,通常的途径是通过以下方式单独获取
get_close_matches()
返回的比赛的比较分数:
match_ratio = difflib.SequenceMatcher(None, 'aple', 'apple').ratio()
这是一种可以将我的速度提高约 10% 的方法...
我使用
get_close_matches()
进行拼写检查,它在后台运行 SequenceMatcher()
,但会删除分数,仅返回匹配字符串的列表。正常情况下。
但是,当前在第 736 行左右对
Lib/difflib.py
进行了小改动,返回可以是一个以分数作为值的字典,因此无需在每个列表项上再次运行 SequenceMatcher
来获取其分数比率。 在示例中,为了清楚起见,我缩短了输出浮点值(如 0.8888888888888888 到 0.889)。输入 n=7 表示如果返回项目超过 7 个(即最高的 7 个),则将返回项目限制为 7 个,并且如果 candidates
很多,则可以应用。
在此示例中,结果通常类似于
['apple', 'staple', 'able', 'lapel']
...如果省略,默认截止值为 0.6(如 Ben 的回答,不做判断)。
在
difflib.py
中很简单(右边这一行显示的是原始内容):
return {v: k for (k, v) in result} # hack to return dict with scores instead of list, original was ... [x for score, x in result]
包括分数,例如
{'apple': 0.889, 'staple': 0.8, 'able': 0.75, 'lapel': 0.667}
>>> to_match = 'aple'
>>> candidates = ['lapel', 'staple', 'zoo', 'able', 'apple', 'appealing']
将最低分数截止/阈值从 0.4 提高到 0.8:
>>> difflib.get_close_matches(to_match, candidates, n=7, cutoff=.4)
{'apple': 0.889, 'staple': 0.8, 'able': 0.75, 'lapel': 0.667, 'appealing': 0.461}
>>> difflib.get_close_matches(to_match, candidates, n=7, cutoff=.7)
{'apple': 0.889, 'staple': 0.8, 'able': 0.75}
>>> difflib.get_close_matches(to_match, candidates, n=7, cutoff=.8)
{'apple': 0.889, 'staple': 0.8}
要获取匹配字符串及其分数的列表,请尝试此解决方案。 转到 difflab.py
return [x for score, x in result]
将其替换为 return [[x,score] for score, x in result]