• Python模糊匹配(fuzzywuzzy package)


    from fuzzywuzzy import fuzz
    from fuzzywuzzy import process
    
    • 1
    • 2

    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
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    2. process method

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

    >>> choices = ["河南省", "郑州市", "湖北省", "武汉市"]
    >>> process.extract("州", choices, limit=2)
    [('郑州市', 90), ('河南省', 0)]
    >>> process.extractOne("州", choices)
    ('郑州市', 90)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    >>> 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)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    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[1].
    2. Python中实现模糊匹配的魔法库:FuzzyWuzzy
  • 相关阅读:
    C++ 虚函数
    SCSI介绍和SCSI命令承载于各类总线的方式
    uniapp自动化测试学习
    Kubernetes教程(五)---Service 的几种访问方式
    Codeforces Round #818 (Div. 2) E. Madoka and The Best University(gcd性质+莫比乌斯反演φ)
    Servlet的运行图解和生命周期
    Flume(二)
    Vue Router完整的导航解析流程
    C++并发编程 - 同步并发操作
    科技云报道:软件定义汽车时代,云计算成幕后重要推手
  • 原文地址:https://blog.csdn.net/zxxr123/article/details/132954042