get_matching_blocks() 忽略某些块,如果它先与后面的块匹配

get_matching_blocks() is ignoring some blocks if it matches first with blocks that come later

这是 python 代码 -

import difflib
x = "abxcd"
y= "cdab"
s = difflib.SequenceMatcher(None, x, y)
for block in s.get_matching_blocks():
    a=block[0:]
    if a[2]>0:
        m=a[0]
        n=a[0]+a[2]
        print (x[m:n])

它只打印出 'ab' 而忽略 'cd'。 但我希望它打印出 'ab' 和 'cd'。 有什么办法吗?

看看get_matching_blocks()

documentation

Return list of triples describing non-overlapping matching subsequences. Each triple is of the form (i, j, n), and means that a[i:i+n] == b[j:j+n]. The triples are monotonically increasing in i and j.

因此,根据您的输入 "abxcd""cdab",它会在 'cdab' 中搜索 'a',它位于位置 2(从 0 开始),然后是 'b' 在位置 '3' 中,这是第二个字符串的最后一个位置。当它到达 'x' 时,第二个字符串迭代已经完成。

>>> s=difflib.SequenceMatcher(None,  "abxcd","cdab")
>>> s.get_matching_blocks()
[Match(a=0, b=2, size=2), Match(a=5, b=4, size=0)]

让我们再举一个例子,其中 x="abxcd"y="abcd" 您将得到 ab, cd 的结果。最初它在位置 0 的 'abcd' 中搜索 'a',在位置 1 中搜索 'b',类似地在 string2 的位置 2 和 3 中搜索 'c' 和 'd'

>>> s=difflib.SequenceMatcher(None,  "abxcd","abcd")
>>> s.get_matching_blocks()
[Match(a=0, b=0, size=2), Match(a=3, b=2, size=2), Match(a=5, b=4, size=0)]