使用像 leveinstein(leveinstein 或 difflib)这样的算法,很容易找到近似匹配。例如。
>>> import difflib
>>> difflib.SequenceMatcher(None,"amazing","amaging").ratio()
0.8571428571428571
可以通过根据需要确定阈值来检测模糊匹配。
当前要求:根据较大字符串中的阈值查找模糊子字符串。
例如。
large_string = "thelargemanhatanproject is a great project in themanhattincity"
query_string = "manhattan"
#result = "manhatan","manhattin" and their indexes in large_string
一种蛮力解决方案是生成所有长度为 N-1 到 N+1(或其他匹配长度)的子字符串,其中 N 是 query_string 的长度,并在它们上一一使用 levenstein 并查看阈值。
python 中是否有更好的解决方案,最好是 python 2.7 中包含的模块,或者外部可用的模块。
---------------------更新和解决方案----------------
Python regex 模块工作得很好,尽管它比用于模糊子字符串情况的内置模块慢一点re
,这是由于额外操作而产生的明显结果。期望的输出是好的,并且可以很容易地定义对模糊程度的控制。
>>> import regex
>>> input = "Monalisa was painted by Leonrdo da Vinchi"
>>> regex.search(r'\b(leonardo){e<3}\s+(da)\s+(vinci){e<2}\b',input,flags=regex.IGNORECASE)
<regex.Match object; span=(23, 41), match=' Leonrdo da Vinchi', fuzzy_counts=(0, 2, 1)>