Python | Find all close matches of an input string from a list

Examples:

 Input: patterns = ['ape',' apple', 'peach',' puppy'], input = 'appel' Output: [' apple', 'ape'] 

We can quickly solve this problem in python using the built-in difflib.get_close_matches () function.

Like the difflib.get_close_matches () function does it work in Python?

difflib.get_close_matches (word, features, n, clipping) takes four parameters where n, clipping are optional.  word — this is a sequence for which a close match is desired, possibilities — it is a list of sequences to which the word is matched. Optional argument n (default 3) — this is the maximum number of close matches to return, n must be greater than 0. Optional argument cutoff (default 0.6) — it is a floating point number in the range [0, 1]. Opportunities that are not rated, at least as a word, are ignored. 
The best (no more than n) matches among the possibilities are returned in a list sorted by similarity score, most similar first.

# Function to find all close matches
# input string in the given list of possible strings

from difflib import get_close_matches

 

def closeMatches (patterns, word):

print (get_close_matches (word, patterns))

 
# Driver program

if __ name__ = = " __main__ " :

  word = 'appel'

  patterns = [ 'ape' , 'apple' , ' peach' , 'puppy' ]

closeMatches (patterns, word)

Links: https://docs.python.org/2/library/difflib.html

Output: 

 ['apple',' ape'] 




Get Solution for free from DataCamp guru