a shot of dev knowledge

Related tags

How to use get_close_matches() in Python

get_close_matches() is a function that is available in the difflib Python package.

The difflib module provides classes and functions for comparing sequences. We can use this module to compare files and produce information about file differences in various formats.

We can use this function to get a list of “good matches” for a particular word.

Parameters

This function accepts four parameters:

  • word: This is the string for which we need the close matches.
  • possibilities: This is usually a list of string values with which the word is matched.
  • n: This is an optional parameter with a default value of 3. It specifies the maximum number of close matches required.
  • cutoff: This is also an optional parameter with a default value of 0.6. It specifies that the close matches should have a score greater than the cutoff.

Return value

The get_close_matches() function returns a list of close matched strings that satisfy the cutoff. The order of close matched string is based on similarity score, so the most similar string comes first in the list.

Code

The code snippet below provides an example of this function.

import difflib

word = "learning"
possibilities = ["love", "learn", "lean", "moving", "hearing"]
n = 3
cutoff = 0.7

close_matches = difflib.get_close_matches(word, 
                possibilities, n, cutoff)

print(close_matches)
Example of get_close_matches() in Python

Explanation:

  • On line 1, we import the required package.
  • From lines 3 to 6, we define the parameters that will be passed to the function.
  • On line 8, we use the get_close_matches() function and pass all the parameters defined in the above step.
  • Finally, on line 11, we print all the close matches.

Now, it is your turn to try out different parameter values in the code editor.

Related tags

RELATED COURSES
View all Courses
Related Courses
Related Courses
View all Courses

Keep Exploring