FuzzyWuzzy 簡介
FuzzyWuzzy 是一個簡單易用的模糊字符串匹配工具包。它依據(jù) Levenshtein Distance 算法 計算兩個序列之間的差異。
Levenshtein Distance
算法,又叫Edit Distance
算法,是指兩個字符串之間,由一個轉(zhuǎn)成另一個所需的最少編輯操作次數(shù)。許可的編輯操作包括將一個字符替換成另一個字符笛粘,插入一個字符,刪除一個字符湿硝。一般來說薪前,編輯距離越小,兩個串的相似度越大关斜。
項目地址:https://github.com/seatgeek/fuzzywuzzy
環(huán)境依賴
- Python 2.7 以上
- difflib
- python-Levenshtein(可選, 在字符串匹配時可提供4-10x 的加速, 但在某些特定情況下可能會導(dǎo)致不同的結(jié)果)
支持的測試工具
- pycodestyle
- hypothesis
- pytest
安裝
使用 PIP 通過 PyPI 安裝
pip install fuzzywuzzy
or the following to install python-Levenshtein
too
pip install fuzzywuzzy[speedup]
使用 PIP 通過 Github 安裝
pip install git+git://github.com/seatgeek/fuzzywuzzy.git@0.17.0#egg=fuzzywuzzy
或者添加你的 requirements.txt
文件 (然后運行 pip install -r requirements.txt
)
git+ssh://git@github.com/seatgeek/fuzzywuzzy.git@0.17.0#egg=fuzzywuzzy
使用 GIT 手工安裝
git clone git://github.com/seatgeek/fuzzywuzzy.git fuzzywuzzy
cd fuzzywuzzy
python setup.py install
用法
>>> from fuzzywuzzy import fuzz
>>> from fuzzywuzzy import process
簡單匹配(Simple Ratio)
>>> fuzz.ratio("this is a test", "this is a test!")
97
非完全匹配(Partial Ratio)
>>> fuzz.partial_ratio("this is a test", "this is a test!")
100
忽略順序匹配(Token Sort Ratio)
>>> fuzz.ratio("fuzzy wuzzy was a bear", "wuzzy fuzzy was a bear")
91
>>> fuzz.token_sort_ratio("fuzzy wuzzy was a bear", "wuzzy fuzzy was a bear")
100
去重子集匹配(Token Set Ratio)
>>> fuzz.token_sort_ratio("fuzzy was a bear", "fuzzy fuzzy was a bear")
84
>>> fuzz.token_set_ratio("fuzzy was a bear", "fuzzy fuzzy was a bear")
100
Process
用來返回模糊匹配的字符串和相似度示括。
>>> choices = ["Atlanta Falcons", "New York Jets", "New York Giants", "Dallas Cowboys"]
>>> process.extract("new york jets", choices, limit=2)
[('New York Jets', 100), ('New York Giants', 78)]
>>> process.extractOne("cowboys", choices)
("Dallas Cowboys", 90)
你可以傳入附加參數(shù)到 extractOne
方法來設(shè)置使用特定的匹配模式。一個典型的用法是來匹配文件路徑:
>>> process.extractOne("System of a down - Hypnotize - Heroin", songs)
('/music/library/good/System of a Down/2005 - Hypnotize/01 - Attack.mp3', 86)
>>> process.extractOne("System of a down - Hypnotize - Heroin", songs, scorer=fuzz.token_sort_ratio)
("/music/library/good/System of a Down/2005 - Hypnotize/10 - She's Like Heroin.mp3", 61)
已知移植
FuzzyWuzzy 已經(jīng)被移植到其他語言環(huán)境痢畜,我們已知的有:
- Java: xpresso's fuzzywuzzy implementation
- Java: fuzzywuzzy (java port)
- Rust: fuzzyrusty (Rust port)
- JavaScript: fuzzball.js (JavaScript port)
- C++: Tmplt/fuzzywuzzy
- C#: fuzzysharp (.Net port)
- Go: go-fuzzywuzz (Go port)