Python“正则表达式"模块:模糊度值 [英] Python "regex" module: Fuzziness value

查看:129
本文介绍了Python“正则表达式"模块:模糊度值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Regex 模块的模糊匹配"功能.

I'm using the "fuzzy match" functionality of the Regex module.

我如何获得匹配"的模糊性值",该值表明该模式与字符串有何不同,就像Levenshtein中的编辑距离"一样?

How can I get the "fuzziness value" of a "match" which indicates how different the pattern is to the string, just like the "edit distance" in Levenshtein?

我以为我可以在Match对象中获取值,但是它不存在.官方文档对此一无所获.

I thought I could get the value in the Match object, but it's not there. The official docs said nothing about it, neither.

例如:

regex.match('(?:foo){e}','for')

a.captures()告诉我单词"for"是匹配的,但我想知道模糊性值,在这种情况下应为1.

a.captures() tells me that the word "for" is matched, but I'd like to know the fuzziness value, which should be 1 in this case.

有什么方法可以实现?

推荐答案

>>> import difflib
>>> matcher = difflib.SequenceMatcher(None, 'foo', 'for')
>>> sum(size for start, end, size in matcher.get_matching_blocks())
2
>>> max(map(len, ('foo', 'for'))) - _
1
>>>
>>>
>>> matcher = difflib.SequenceMatcher(None, 'foo', 'food')
>>> sum(size for start, end, size in matcher.get_matching_blocks())
3
>>> max(map(len, ('foo', 'food'))) - _
1

http://docs.python.org/2/library/difflib.html#difflib.SequenceMatcher.get_matching_blocks http://docs.python.org/2/library/difflib .html#difflib.SequenceMatcher.get_opcodes

这篇关于Python“正则表达式"模块:模糊度值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆