Python “regex” module: Fuzziness value

倾然丶 夕夏残阳落幕 提交于 2019-12-01 04:11:02

问题


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

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?

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

e.g.:

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

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.

Is there any way to achieve that?


回答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




回答2:


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

this returns a tuple (x,y,z) where:

x = number of substitutions

y = number of insertions and

z = number of deletions

But this is not always a reliable count, ie: the regex match fuzziness night not equate to the true Levinstein distance in some cases

Python regex module fuzzy match: substitution count not as expected



来源:https://stackoverflow.com/questions/17023862/python-regex-module-fuzziness-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!