FuzzyWuzzy Python庫
在本教程中,我們將學習關於**FuzzyWuzzy** Python庫。**FuzzyWuzzy**庫用於比較兩個字串。我們還有其他模組,如**regex**和**difflib**也可以用來比較字串。但是,**FuzzyWuzzy** 的獨特之處在於,它返回的匹配分數是0到100之間的數值,而不是**真、假或字串**。
要使用**FuzzyWuzzy**庫,我們必須安裝**fuzzywuzzy**和**python-Levenshtein**。執行以下命令來安裝它們。
pip install fuzzywuzzy
如果您執行上述命令,將會看到以下成功訊息。
Collecting fuzzywuzzy Downloading https://files.pythonhosted.org/packages/d8/f1/5a267addb30ab7eaa1beab2 b9323073815da4551076554ecc890a3595ec9/fuzzywuzzy-0.17.0-py2.py3-none-any.whl Installing collected packages: fuzzywuzzy Successfully installed fuzzywuzzy-0.17.0
在Linux系統中執行以下命令來安裝**python-Levenshtein**。
pip install python-Levenshtein
在Windows系統中執行以下命令。
easy_install python-Levenshtein
fuzz 模組
現在,我們將學習**fuzz**模組。**fuzz**用於一次比較兩個字串。它有不同的方法,返回0到100之間的分數。讓我們看看fuzz模組的一些方法。
fuzz.ratio()
讓我們看看**fuzz**模組的第一個方法**ratio**。它用於比較兩個字串,並返回0到100之間的分數。請參見下面的示例以更清晰地瞭解。
示例
## importing the module from the fuzzywuzzy library
from fuzzywuzzy import fuzz
## 100 for same strings
print(f"Equal Strings:- {fuzz.ratio('tutorialspoint', 'tutorialspoint')}")
## random score for slight changes in the strings
print(f"Slight Changed Strings:- {fuzz.ratio('tutorialspoint', 'TutorialsPoint')}")
print(f"Slight Changed Strings:- {fuzz.ratio('tutorialspoint', 'Tutorials Point')}"
)
## complete different strings
print(f"Different Strings:- {fuzz.ratio('abcd', 'efgh')}")輸出
Max Score:- 100 Slight Changed Strings:- 86 Slight Changed Strings:- 86 Different Strings:- 0
儘可能多地嘗試使用**partial_ratio**,以便更好地理解。
fuzz.WRatio()
**fuzz.WRatio()**處理大小寫和其他一些引數。讓我們看一些例子。
示例
## importing the module from the fuzzywuzzy library
from fuzzywuzzy import fuzz
## 100 score even if one string contains more characters than the other
print(f"Max Score:- {fuzz.WRatio('tutorialspoint', 'tutorialspoint!!!')}")
## random score for slight changes in the strings
print(f"Slight Changed Strings:- {fuzz.WRatio('tutorialspoint', 'TutorialsPoint')}")
print(f"Slight Changed Strings:- {fuzz.WRatio('tutorialspoint', 'TutorialsPoint')}")
## complete different strings
print(f"Different Strings:- {fuzz.ratio('abcd', 'efgh')}")輸出
Max Score:- 100 Slight Changed Strings:- 100 Slight Changed Strings:- 100 Different Strings:- 0
正如我們所看到的,**WRatio**忽略大小寫和一些額外的字元。使用**WRatio**而不是簡單的ratio可以讓你得到更接近的匹配字串。
結論
如果您對本教程有任何疑問,請在評論區提出。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP