加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-20 13:35:06 所属栏目:Python 来源:网络整理
导读:我正在使用 Regex模块的“模糊匹配”功能. 如何获得“匹配”的“模糊值”,表明模式与字符串有多么不同,就像Levenshtein中的“编辑距离”一样? 我以为我可以在Match对象中获取值,但它不存在.官方文件也没有提及任何相关内容. 例如.: regex.match('(?:foo){e
我正在使用 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,'food')
>>> sum(size for start,size in matcher.get_matching_blocks())
3
>>> max(map(len,'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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读