Python“正则表达式”模块:模糊值


问题内容

我正在使用Regex模块的“模糊匹配”功能。

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

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

例如:

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

a.captures()告诉我“ for”一词是匹配的,但我想知道模糊性值,1在这种情况下应该如此。

有什么办法可以实现?


问题答案:
>>> 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