我一直在研究如何找到有效的解决方案。我研究了差异引擎(谷歌的diff-match-patch,python的diff)和一些最长的通用链算法。
我希望能收到你们关于如何解决此问题的建议。您想特别推荐任何算法或库吗?
我不知道“最长共同的[[chain?substring?]]”与“ percent Difference”有什么关系,尤其是在评论中看到您期望两个字符串中的一个字符相差很小时,%差异很小。中间(因此它们最长的公共子字符串大约是字符串长度的一半)。
忽略“最长共同点”的陌生性,并将“百分比差异”定义为字符串之间的编辑距离除以最大长度(当然是100倍;-),那么:
def levenshtein_distance(first, second): """Find the Levenshtein distance between two strings.""" if len(first) > len(second): first, second = second, first if len(second) == 0: return len(first) first_length = len(first) + 1 second_length = len(second) + 1 distance_matrix = [[0] * second_length for x in range(first_length)] for i in range(first_length): distance_matrix[i][0] = i for j in range(second_length): distance_matrix[0][j]=j for i in xrange(1, first_length): for j in range(1, second_length): deletion = distance_matrix[i-1][j] + 1 insertion = distance_matrix[i][j-1] + 1 substitution = distance_matrix[i-1][j-1] if first[i-1] != second[j-1]: substitution += 1 distance_matrix[i][j] = min(insertion, deletion, substitution) return distance_matrix[first_length-1][second_length-1] def percent_diff(first, second): return 100*levenshtein_distance(a, b) / float(max(len(a), len(b))) a = "the quick brown fox" b = "the quick vrown fox" print '%.2f' % percent_diff(a, b)
Levenshtein函数来自Stavros的博客。在这种情况下,结果将是5.26(差异百分比)。