这篇文章主要介绍了Python实现字符串模糊匹配方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
Python字符串模糊匹配
Python的difflib库中get_close_matches方法
包含四个参数
x
:被匹配的字符串。words
:去匹配的字符串列表。n
,前topn个最佳匹配返回,默认为3。cutoff
:匹配度大小,为[0, 1]浮点数,默认数值0.6。
1 2 3 4 | import difflib list1 = [ 'ape' , 'apple' , 'peach' , 'puppy' ] difflib.get_close_matches( 'appel' , list1) |
1 2 3 | import keyword difflib.get_close_matches( 'wheel' , keyword.kwlist) |
1 | difflib.get_close_matches( 'pineapple' , keyword.kwlist) |
![](https://i-blog.csdnimg.cn/blog_migrate/3d1dd8ff36252e8f9a24ca2be84875cc.png)
1 | difflib.get_close_matches( 'accept' , keyword.kwlist) |
![](https://i-blog.csdnimg.cn/blog_migrate/705b48da5e05f47861d2590ea93b9af1.png)
利用这个功能就能够实现SQL中的LIKE模糊查询。
python-re模块,模糊匹配
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | import re def fuzzyMatch(): value = '冬冬' list = [ '大海冬冬的' , '一起冬冬' , '打架' , '东方都好' , '冬冬大化' ] pattern = '.*' + value + '.*' for s in list : obj = re.findall(pattern, s) if len (obj) > 0 : a = s print (a) break fuzzyMatch() |
以上为个人经验,希望能给大家一个参考,
转自:https://www.weidianyuedu.com