FuzzyWuzzy Python库

在本教程中,我们将学习FuzzyWuzzy Python库。开发了FuzzyBuzzy库以与字符串进行比较。我们还有其他模块,例如regexdifflib来比较字符串。但是,FuzzyBuzzy在其方式上是独一无二的。该库中的方法返回的分数是匹配的字符串的100分(而不是true,false或string)

要使用FuzzyWuzzy库,我们必须安装Fuzzywuzzypython- 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用于一次比较两个字符串。它有不同的方法来返回分数(满分为100)。让我们看一下模糊模块的一些方法。

fuzz.ratio()

让我们看看模糊模块比率的第一种方法。它用于比较两个得分均不超过100的字符串。请参阅下面的示例以清楚地了解。

示例

## importing the module from the fuzzywuzzy library
from fuzzywuzzy import fuzz
## 100 for same strings
print(f"Equal Strings:- {fuzz.ratio('nhooo', 'nhooo')}")
## random score for slight changes in the strings
print(f"Slight Changed Strings:- {fuzz.ratio('nhooo', 'nhooo')}")
print(f"Slight Changed Strings:- {fuzz.ratio('nhooo', 'nhooo.com')}"
)
## 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('nhooo', 'nhooo!!!')}")
## random score for slight changes in the strings
print(f"Slight Changed Strings:- {fuzz.WRatio('nhooo', 'nhooo')}")
print(f"Slight Changed Strings:- {fuzz.WRatio('nhooo', 'nhooo')}")
## 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而不是简单的比率可以使您更接近匹配的字符串。

结论