Saturday, December 28, 2024
Google search engine
HomeLanguagesPython – Find the Levenshtein distance using Enchant

Python – Find the Levenshtein distance using Enchant

Levenshtein distance between two strings is defined as the minimum number of characters needed to insert, delete or replace in a given string string1 to transform it to another string string2.

Examples :

Input : string1 = “geek”, string2 = “gesek”
Output : 1
Explanation : We can convert string1 into str2 by inserting a ‘s’.

Input : str1 = “cat”, string2 = “cut”
Output : 1
Explanation : We can convert string1 into str2 by replacing ‘a’ with ‘u’.

Input : string1 = “sunday”, string2 = “saturday”
Output : 3
Explanation : Last three and first characters are same. We basically need to convert “un” to “atur”. This can be done using below three operations. Replace ‘n’ with ‘r’, insert t, insert a

The Levenshtein distance between two strings can be found using the enchant.utils.levenshtein() method of the enchant module.

enchant.utils.levenshtein()

Syntax : enchant.utils.levenshtein(string1, string2)

Parameters :
string1 : the first string to be compared
string2 : the second string to be compared

Returns : an integer denoting the Levenshtein distance

Example 1:




# import the enchant module
import enchant
  
# determining the values of the parameters
string1 = "abc"
string2 = "aef"
  
# the Levenshtein distance between
# string1 and string2
print(enchant.utils.levenshtein(string1, string2))


Output :

2

Example 2:




# import the enchant module
import enchant
  
# determining the values of the parameters
string1 = "Hello World"
string2 = "Hello d"
  
# the Levenshtein distance between
# string1 and string2
print(enchant.utils.levenshtein(string1, string2))


Output :

4

Example 3:




# import the enchant module
import enchant
  
# determining the values of the parameters
string1 = "Computer Science Portal"
string2 = "Computer Portal"
  
# the Levenshtein distance between
# string1 and string2
print(enchant.utils.levenshtein(string1, string2))


Output :

8

Last Updated :
26 May, 2020
Like Article
Save Article

<!–

–>

Similar Reads
Related Tutorials
RELATED ARTICLES

Most Popular

Recent Comments