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 to x 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; when n=None, the function returns the entire lookup_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:

  • kwargs – [Optional] Additional parameters for the chosen engine; for instance, cutoff for 'difflib' and score_cutoff for 'rapidfuzz'.

Returns:

A string or list of strings similar to x, depending on n and the engine used.

Return type:

str | list | None

Note

  • By default, the function uses the built-in difflib module.

  • When engine='rapidfuzz' (or simply, engine='fuzz'), the function relies on RapidFuzz, which is not a dependency of pyhelpers. Install it separately using pip or conda.

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']