get_close_matches() in Python














































get_close_matches() in Python



get_close_matches()

get_close_matches() is a method of difflib python package.

 As the name suggests this tool returns a list of closed
 matched strings that satisfy the cutoff. 
The get_close_matches() method takes in four parameters of
 which for finding the matches of which two are optional. Following are the
 parameters that it accepts.

  •     Word: This is the single input string for which the closest matches are found.
  • Possibilities:This is the list of pattern strings with which the input string is matched
  •      n: This is an optional parameter. This specifies the maximum number of close matches  required for the input string. The default value for this parameter is 3.
  •      Cutoff: This is an optional parameter. This determines similarity between two words need to be in             order to be returned as output. Possibilities that don’t score at least that similar to word are  ignored. This argument is in the range of [0,1] and its default value is 0.6.

 Thus the Syntax of get_close_matches() is:

        get_close_matches(word,possibilities,n,cutoff)


 Lets take an Example

CODE

  import difflib

  from difflib import get_close_matches

  possibilities=[
'pythonsecrets', 'cpp', 'c', 'python','linux']

  match = get_close_matches(
'cppsecrets',possibilities,n=4,cutoff=0.2)

  print("Best matches:"
, match)



OUTPUT




In the above code possibilities is the pattern of of strings that is go
be matched with the word that is the input string "cppsecrets".
The cutoff parameter is taken as 0.2 whereas the maximum number of close matches to be returned is taken as n=4.

Thus the close matches are returned in "Best matches" list.


Comments