1

假设我们有两个例子:

一:

a = "Six d.o.g.s."
b = "six d.o.g.s"

二:

c = "Death Disco"
d = "deathdisco"
e = "deathdisco666"

两者略有不同。第一个有一个点,第二个之间没有空格。有些是小写的。


客观的:

  • 对于给定的, 如果它们有两个字母“错误” ab我们想a.lower()==b.lower()给出。true

  • 因为“错误”只有一个空格,所以candd为真。

  • 但是对于cand e,虽然 thee的长度多了两个字母(与 相比c),但我们有三个不同的字母。

我怎么能用python做到这一点?通过正则表达式还是有类似目的的库?

4

1 回答 1

0

因此,鉴于 minitech 的评论,我编写了我发现的代码:

def levenshtein(seq1, seq2):
    oneago = None
    thisrow = range(1, len(seq2) + 1) + [0]
    for x in xrange(len(seq1)):
        twoago, oneago, thisrow = oneago, thisrow, [0] * len(seq2) + [x + 1]
        for y in xrange(len(seq2)):
            delcost = oneago[y] + 1
            addcost = thisrow[y - 1] + 1
            subcost = oneago[y - 1] + (seq1[x] != seq2[y])
            thisrow[y] = min(delcost, addcost, subcost)
    return thisrow[len(seq2) - 1]


print levenshtein(a,b) < 2
于 2013-11-07T14:45:47.373 回答