FuzzyWuzzy Python 库

pythonserver side programmingprogramming

在本教程中,我们将学习 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

现在,我们将了解 fuzz 模块。fuzz 用于一次比较两个字符串。它有不同的方法返回 100 分制的分数。让我们看看 fuzz 模块的一些方法。

fuzz.ratio()

让我们看看 fuzz 模块 ratio 的第一个方法。它用于比较两个字符串,返回 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 而不是简单的比率可以为您提供更接近匹配的字符串。

结论

如果您对本教程有任何疑问,请在评论部分中提及。


相关文章