Find all close matches of input string from a list in Python

PythonServer Side ProgrammingProgramming

Suppose we are given a word and we want to find its closest matches. Not an exact match but other words which have some close resemblance in pattern with the given word. For this we use a module called difflib and use its method named get_close_matches.


This method is part of the module difflib and gives us the match with possible patterns which we specify. Below is the syntax.

difflib.get_close_matches(word, possibilities, n, cutoff)
word: It is the word to which we need to find the match.
Possibilities: This is the patterns which will be compared for matching.
n: Maximum number of close matches to return. Should be greater than 0.
Cutoff: The possibilities that do not score this float value between 0 and 1 are ignored.

Running the above code gives us the following result −


In the below example we take a word and also a list of possibilities or patterns that need to be compared. Then we apply the method to get the result needed.

 Live Demo

from difflib import get_close_matches

word = 'banana'
patterns = ['ana', 'nana', 'ban', 'ran','tan']

print('matched words:',get_close_matches(word, patterns))


Running the above code gives us the following result −

matched words: ['nana', 'ban', 'ana']
Updated on 26-Aug-2020 07:28:33