反转python 2.7中difflib的get_matching_blocks结果并获取MISMATCHED块

时间:2019-07-17 20:43:24

标签: python python-2.7 difflib

以下python 2.7示例返回string1和string2之间的匹配块:

import difflib    

string1 = "This is a test"
string2 = "This ain't a testament"

s = difflib.SequenceMatcher(lambda x: x == " ", string1, string2)

for block in s.get_matching_blocks():
    a,b,size = block
    print "string1[%s] and string2[%s] match for %s characters" % block

以下是上述程序的结果:

string1[0] and string2[0] match for 5 characters
string1[5] and string2[6] match for 1 characters
string1[7] and string2[10] match for 7 characters
string1[14] and string2[22] match for 0 characters

我想反转结果并返回string1和string2的不匹配块,如下所示:

string1[6] mismatch for 1 characters

string2[5] mismatch for 1 characters
string2[7] mismatch for 3 characters
string2[17] mismatch for 5 characters

注意:两个字符串的匹配块总数相同,但是不匹配的块将根据字符串而有所不同。

这里是字符串的颜色编码表示,其中black = matched和red = mismatched。

enter image description here

1 个答案:

答案 0 :(得分:0)

在我看来,应该可以通过匹配的块来计算不匹配的部分。下面粘贴了一个快速解决方案(称为“仅使用问题中的输入进行了测试”)。看看它是否可以帮助您制定最终的解决方案。

注意:我现在只能访问Python3解释器,但是由于此问题不是特定于版本的,因此我将发布此解决方案。

import difflib

string1 = "This is a test"
string2 = "This ain't a testament"

s = difflib.SequenceMatcher(lambda x: x == " ", string1, string2)

s1_miss = list()
s2_miss = list()
s1_cur_off = 0
s2_cur_off = 0
for block in s.get_matching_blocks():
    a,b,size = block
    print("string1[%s] and string2[%s] match for %s characters" % block)
    if a > s1_cur_off:
        s1_miss.append((s1_cur_off, a-1, a-1-s1_cur_off + 1))
    s1_cur_off = a + size
    if b > s2_cur_off:
        s2_miss.append((s2_cur_off, b-1, b-1-s2_cur_off + 1))
    s2_cur_off = b + size
print(s1_miss)
print(s2_miss)

输出: 将为每个字符串转储不匹配的列表。列表中的每个元素都有三元组:不匹配的起始偏移量和结束偏移量以及长度(主要用于调试)。

string1[0] and string2[0] match for 5 characters
string1[5] and string2[6] match for 1 characters
string1[7] and string2[10] match for 7 characters
string1[14] and string2[22] match for 0 characters
[(6, 6, 1)]
[(5, 5, 1), (7, 9, 3), (17, 21, 5)]