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

2024-05-29 10:55:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在标准算法中添加两个修改。在

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

说我有个词“笼”。“cage”和“cage”之间的hamming距离为0(第一个字母)。任何其他字母都是0.5。(说“cage”和“cage”。在

第二,“cage”和“caKe”是1.5(不同的字母=1加上不同的大写字母=0.5),3,“caKe”和“caqe”是0(考虑k和q是同一个字母)。在

同样的规则也适用于长句。(说“生日快乐”和“百日快乐”距离=1+1+0.5=2.5)

我想通过任何一组单词/句子和修改算法而不是标准算法需要适用。在

我用python为案例1编写了一个示例代码,但无法理解如何继续使用大写。在

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

附言:用R作任何解释都很好。在


Tags: 字符串文本算法距离标准len字母大写字母
1条回答
网友
1楼 · 发布于 2024-05-29 10:55:42

看看这段代码-我也对它做了解释。在

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

我不知道为什么要调用两次字符串长度的函数。我已经试过了,效果和你预期的一样。希望这有帮助!在

相关问题 更多 >

    热门问题