Python – Find the Levenshtein distance using Enchant
Last Updated :
26 May, 2020
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 enchant
string1 = "abc"
string2 = "aef"
print (enchant.utils.levenshtein(string1, string2))
|
Output :
2
Example 2:
import enchant
string1 = "Hello World"
string2 = "Hello d"
print (enchant.utils.levenshtein(string1, string2))
|
Output :
4
Example 3:
import enchant
string1 = "Computer Science Portal"
string2 = "Computer Portal"
print (enchant.utils.levenshtein(string1, string2))
|
Output :
8
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...