使用Fuzzy Wuzzy匹配姓名时短字符串得分过高如何优化
Fuzzy Wuzzy短字符串匹配分数过高的调整方案
你使用的fuzz.WRatio本身内置了短字符串匹配加权逻辑,对前缀匹配的短查询会额外提升分数,同时会弱化长度差异的惩罚,所以长度为2的"sa"匹配到开头带"sa"的长字符串时,会得到远高于实际编辑距离的分数。
可用调整方案
1. 更换无加权的基础评分器
直接替换scorer参数为fuzz.ratio,该评分器严格基于莱文斯坦编辑距离计算分数,不会做额外加权,更符合你对匹配分数的预期:
text_to_match = "sa" print(process.extract(text_to_match, ['sachin','saurabh','Amol'],scorer=fuzz.ratio))
运行结果示例:
[('sachin', 36), ('saurabh', 33), ('Amol', 0)]
如果需要保留部分匹配逻辑但不需要加权,可以选择fuzz.partial_ratio替代。
2. 增加最低分数阈值过滤
如果你需要保留WRatio的其他特性,可以在调用process.extract时添加score_cutoff参数,直接过滤掉低于阈值的结果:
text_to_match = "sa" print(process.extract(text_to_match, ['sachin','saurabh','Amol'],scorer=fuzz.WRatio, score_cutoff=95))
该示例中阈值设为95,所有低于95分的结果都会被排除,最终返回空列表。
3. 自定义带长度惩罚的评分函数
如果默认评分器都不符合你的业务需求,可以自行封装评分逻辑,在原有评分基础上根据字符串长度差做额外惩罚:
def custom_scorer(str1, str2): base_score = fuzz.WRatio(str1, str2) len_gap = abs(len(str1) - len(str2)) # 长度差超过2时,每差1个字符扣10%的分数 if len_gap > 2: base_score = base_score * (1 - (len_gap - 2) * 0.1) return int(base_score) text_to_match = "sa" print(process.extract(text_to_match, ['sachin','saurabh','Amol'],scorer=custom_scorer))
运行结果示例:
[('sachin', 54), ('saurabh', 54), ('Amol', 0)]
内容的提问来源于stack exchange,提问作者Gupta
相关产品推荐
相关产品推荐

