find_similar_str¶
- pyhelpers.text.find_similar_str(x, lookup_list, n=1, ignore_punctuation=True, engine='difflib', **kwargs)[source]¶
Finds
n
strings that are similar tox
from a sequence of candidates.- Parameters:
x (str) – The string to find similar matches for.
lookup_list (Iterable) – A sequence of strings to search for matches.
n (int | None) – Number of similar strings to return; defaults to
1
; whenn=None
, the function returns the entirelookup_list
sorted by similarity in descending order.ignore_punctuation (bool) – Whether to ignore punctuation in the comparison; defaults to
True
.engine (str | Callable) –
Method for finding similarities; options include:
'difflib'
(default), which uses difflib.get_close_matches().'rapidfuzz'
(or'fuzz'
), which uses rapidfuzz.fuzz.QRatio().
kwargs – [Optional] Additional parameters for the chosen engine; for instance,
cutoff
for'difflib'
andscore_cutoff
for'rapidfuzz'
.
- Returns:
A string or list of strings similar to
x
, depending onn
and theengine
used.- Return type:
str | list | None
Note
Examples:
>>> from pyhelpers.text import find_similar_str >>> lookup_lst = ['Anglia', ... 'East Coast', ... 'East Midlands', ... 'North and East', ... 'London North Western', ... 'Scotland', ... 'South East', ... 'Wales', ... 'Wessex', ... 'Western'] >>> y = find_similar_str(x='angle', lookup_list=lookup_lst) >>> y 'Anglia' >>> y = find_similar_str(x='angle', lookup_list=lookup_lst, n=2) >>> y ['Anglia', 'Wales'] >>> y = find_similar_str(x='angle', lookup_list=lookup_lst, engine='fuzz') >>> y 'Anglia' >>> y = find_similar_str('angle', lookup_lst, n=2, engine='fuzz') >>> y ['Anglia', 'Wales'] >>> y = find_similar_str(x='x', lookup_list=lookup_lst) >>> y is None True >>> y = find_similar_str(x='x', lookup_list=lookup_lst, cutoff=0.25) >>> y 'Wessex' >>> y = find_similar_str(x='x', lookup_list=lookup_lst, n=2, cutoff=0.25) >>> y 'Wessex' >>> y = find_similar_str(x='x', lookup_list=lookup_lst, engine='fuzz') >>> y 'Wessex' >>> y = find_similar_str(x='x', lookup_list=lookup_lst, n=2, engine='fuzz') >>> y ['Wessex', 'Western']