from fuzzywuzzy import fuzz
from fuzzywuzzy import process

1.关键方法说明

  1. ratio 要字符完全一致,匹配精度才较高
  2. partial_ratio 要字符部分一致,匹配精度较高
  3. token_sort_ratio 即使字符顺序不一致,也能较好匹配
  4. token_set_ratio 即使字符顺序不一致且字符有重复,也能较好匹配
>>> fuzz.ratio("西藏 自治区", "自治区 西藏")
50
>>> fuzz.partial_ratio("西藏 自治区", "自治区 西藏")
50
>>> fuzz.ratio('I love YOU','YOU LOVE I')
30
>>> fuzz.partial_ratio('I love YOU','YOU LOVE I')
30
>>> fuzz.token_sort_ratio("西藏 自治区", "自治区 西藏") 
100
>>> fuzz.token_sort_ratio('I love YOU','YOU LOVE I')
100
>>> fuzz.ratio("西藏 西藏 自治区", "自治区 西藏")
40
>>> fuzz.token_sort_ratio("西藏 西藏 自治区", "自治区 西藏")
80
>>> fuzz.token_set_ratio("西藏 西藏 自治区", "自治区 西藏")
100

2. process method

process.extractprocess.extractOne方法,可以在针对一个字符串,在一个list字符串中找出相似的。不同的是process.extract可以通过limit设置返回的匹配数量,extractOne则仅能返回一个。上述关键方法,可以通过scorer参数来设置。

>>> choices = ["河南省", "郑州市", "湖北省", "武汉市"]
>>> process.extract("州", choices, limit=2)
[('郑州市', 90), ('河南省', 0)]
>>> process.extractOne("州", choices)
('郑州市', 90)
>>> choices = ["河南省", "郑州市", "湖北省", "武汉市"]
>>> process.extract("州郑 ", choices, limit=2)
[('郑州市', 45), ('河南省', 0)]
>>> process.extractOne("州郑 ", choices)
('郑州市', 45)
>>> process.extract("州郑 ", choices, limit=2, scorer=fuzz.token_set_ratio)
[('郑州市', 40), ('河南省', 0)]
>>> process.extractOne("州郑 ", choices, scorer=fuzz.token_set_ratio)
('郑州市', 40)

3. 参考信息

  1. Fuzzywuzzy use the Levenshtein distance to measure the difference between strings.In information theory, linguistics, and computer science, the Levenshtein distance is a string metric for measuring the difference between two sequences. Informally, the Levenshtein distance between two words is the minimum number of single-character edits (insertions, deletions or substitutions) required to change one word into the other.
  2. Python中实现模糊匹配的魔法库:FuzzyWuzzy
09-18 11:12