FuzzyWuzzy is a Python library for fuzzy string matching that uses Levenshtein Distance to compare two strings and returns a similarity score from 0 to 100.
Requirements
- Python 2.7 or higher
- python-Levenshtein
- difflib
Installation
To install the FuzzyWuzzy Python library, use:
pip install fuzzywuzzy
pip install python-Levenshtein
How to use FuzzyWuzzy Python Library?
Import the library:
from fuzzywuzzy import fuzz
from fuzzywuzzy import process
Simple Ratio
The simple ratio measures similarity between two strings.
fuzz.ratio('geeksforgeeks', 'geeksgeeks')
fuzz.ratio('GeeksforGeeks', 'GeeksforGeeks')
fuzz.ratio('geeks for geeks', 'Geeks For Geeks')
Partial ratio
Ignores extra characters at the start or end of a string.
fuzz.partial_ratio("geeks for geeks", "geeks for geeks!") # 100
fuzz.partial_ratio("geeks for geeks", "geeks geeks") # 64
Token Sort
Ignores word order by sorting tokens first.
fuzz.token_sort_ratio("geeks for geeks", "for geeks geeks") # 100
Token Set Ratio
Ignores duplicate words and order.
fuzz.token_set_ratio("geeks for geeks", "geeks for for geeks")
Using process for Lists
If you have a list of strings and want the closest match.
query = 'geeks for geeks'
choices = ['geek for geek', 'geek geek', 'g. for geeks']
process.extract(query, choices)
process.extractOne(query, choices)
WRatio
WRatio is an advanced ratio that gives a more accurate similarity score, handling case and minor differences.
fuzz.WRatio('geeks for geeks', 'Geeks For Geeks')
fuzz.WRatio('geeks for geeks!!!','geeks for geeks')
fuzz.ratio('geeks for geeks!!!','geeks for geeks')
Full Code
from fuzzywuzzy import fuzz
from fuzzywuzzy import process
s1 = "I love GeeksforGeeks"
s2 = "I am loving GeeksforGeeks"
print("FuzzyWuzzy Ratio: ", fuzz.ratio(s1, s2))
print("FuzzyWuzzy PartialRatio: ", fuzz.partial_ratio(s1, s2))
print("FuzzyWuzzy TokenSortRatio: ", fuzz.token_sort_ratio(s1, s2))
print("FuzzyWuzzy TokenSetRatio: ", fuzz.token_set_ratio(s1, s2))
print("FuzzyWuzzy WRatio: ", fuzz.WRatio(s1, s2))
query = 'geeks for geeks'
choices = ['geek for geek', 'geek geek', 'g. for geeks']
print("\nList of ratios: ")
print(process.extract(query, choices))
print("\nBest among the above list: ", process.extractOne(query, choices))
Output
FuzzyWuzzy Ratio: 84
FuzzyWuzzy PartialRatio: 85
FuzzyWuzzy TokenSortRatio: 84
FuzzyWuzzy TokenSetRatio: 86
FuzzyWuzzy WRatio: 84List of ratios:
[('g. for geeks', 95), ('geek for geek', 93), ('geek geek', 86)]
Best among the above list: ('g. for geeks', 95)