修改 python 中两个文本字符串之间的编辑距离算法

modify edit distance algorithm between two text strings in python

我正在尝试对标准算法添加两个修改。

我的字符串区分文本和大小写。

说我有话"cage"。 "cage" 和 "Cage" 之间的汉明距离为 0(第一个字母)。任何其他字母都是 0.5。 (例如,"cage" 和 "cAge"。

两个,"cage"和"caKe"会是1.5(不同的字母=1加上不同的大写=0.5),三个,"cake"和"caqe"会是0(认为 k 和 q 是同一个字母)。

同样的规则也适用于长句。 (比如 "Happy Birthday" 和 "happy BudthDay" 距离 = 1+1+0.5=2.5)

我想传入任何一组 words/sentences 并且修改算法而不是标准算法需要适用。

我已经在 python 中为案例 1 编写了示例代码,但无法理解如何进行大写。

 def editDistance(str1, str2):  if str1[1]==str2[1]:
            return editDistance(str1,str2)
 print editDistance(str1, str2, len(str1), len(str2))

PS:R 中的任何解释也很好。

检查此代码 - 我也提出了反对意见以供解释。

def editDistance(str1, str2):
    if (str1 == str2): # if both strings equal, print 0
        print 0
    else:
        counter = 0
        for c in range(1, len(str1)-1): # iterate through each character in string
            if (str1[c] == str2[c]): # if characters are equal, don't increment counter
                counter += 0
            elif (((str1[c].lower()) == str2[c]) or ((str2[c].lower()) == str1[c])):
                counter += 0.5 # if the lowercase of characters are equal, increment 0.5
            elif ((str1[c].islower()) and (str2[c].islower())):
                counter += 1 # else if both unequal, both lowercase, increment 1
            elif ((str1[c].isupper()) and (str2[c].isupper())):
                counter += 1 # else if both unequal, both uppercase, increment 1
            else:
                counter += 1.5 # reaches here if both unequal and different case, so 1.5
        print counter

editDistance(str1, str2); # call the function with the strings

我不确定你为什么要用字符串的长度调用函数两次。我已经试过了,它按你预期的那样工作。希望这对您有所帮助!