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可以让你得到更接近的匹配字符串。

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

结论

如果您对本教程有任何疑问,请在评论区提出。

更新于:2019年10月23日

浏览量:538

开启你的职业生涯

完成课程获得认证

开始学习
广告