编程语言
首页 > 编程语言> > Python“正则表达式”模块:模糊值

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

标签:python,regex,fuzzy-comparison,pypi-regex
来源: https://codeday.me/bug/20190709/1409496.html