Python – 使用 Enchant 查找 Levenshtein 距离
两个字符串之间的 Levenshtein 距离定义为在给定字符串string1 中插入、删除或替换以将其转换为另一个字符串string2 所需的最小字符数。
例子 :
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
可以使用enchant
模块的enchant.utils.levenshtein()
方法找到两个字符串之间的 Levenshtein 距离。
附魔.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
# 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))
输出 :
2
示例 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))
输出 :
4
示例 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))
输出 :
8
在评论中写代码?请使用 ide.geeksforgeeks.org,生成链接并在此处分享链接。