在Python中进行字符串模糊匹配,你可以使用以下几种方法:
1. 使用`re`模块进行正则表达式匹配:
import re
teststr = "你好,hello,world"
pattern1 = "llo"
r1 = re.search(pattern1, teststr)
if r1:
print(pattern1, "匹配成功.")
else:
print(pattern1, "匹配失败.")
2. 使用`difflib`模块中的`get_close_matches`方法:
import difflib
list1 = ['ape', 'apple', 'peach', 'puppy']
print(difflib.get_close_matches('appel', list1))
3. 使用第三方库`fuzzywuzzy`(注意:旧名称是`thefuzz`):
from fuzzywuzzy import fuzz
ST1 = "Just a test"
ST2 = "just a test"
print(fuzz.ratio(ST1, ST2)) 输出相似度得分
4. 使用`python-Levenshtein`库计算编辑距离:
from Levenshtein import distance
str1 = "apple"
str2 = "appel"
print(distance(str1, str2)) 输出编辑距离
5. 使用`thefuzz`库的`process`模块进行更复杂的模糊匹配:
from thefuzz import fuzz, process
ST1 = "Just a test"
ST2 = "just a test"
print(fuzz.token_sort_ratio(ST1, ST2)) 输出基于标记排序的相似度得分
选择哪种方法取决于你的具体需求,例如,如果你需要更灵活的匹配模式,可以使用正则表达式;如果你需要计算字符串之间的相似度,可以使用`fuzzywuzzy`或`python-Levenshtein`库。