文本对齐:使用python提取匹配序列

Tig*_*er1 5 python text alignment sequence

我的目标是在两个文本段落中提取对齐的匹配序列.接下来是我的文字:

txt1='the heavy lorry crashed into the building at midnight'
txt2='what a heavy lorry it is that crashed into the building'
Run Code Online (Sandbox Code Playgroud)

预期产量:

'heavy lorry'
'crashed into the building'
Run Code Online (Sandbox Code Playgroud)

我的尝试:

def sequ(s1,s2):
    _split1=s1.split()
    _split2=s2.split()
    _match=''.join(list(set(_split1) & set(_split2)))
    return _match

print sequ(txt1, txt2)

Result: heavybuildingintocrashedthelorry
Run Code Online (Sandbox Code Playgroud)

......扭曲的结果.

有关如何达到预期结果的任何建议?谢谢.

fal*_*tru 7

difflib.SequenceMatcher.get_matching_blocks 完全符合你的要求.

import difflib

def sequ(s1, s2):
    words1 = s1.split()
    words2 = s2.split()
    matcher = difflib.SequenceMatcher(a=words1, b=words2)
    for block in matcher.get_matching_blocks():
        if block.size == 0:
            continue
        yield ' '.join(words1[block.a:block.a+block.size])

txt1 = 'the heavy lorry crashed into the building at midnight'
txt2 = 'what a heavy lorry it is that crashed into the building'
print list(sequ(txt1, txt2))
Run Code Online (Sandbox Code Playgroud)

输出:

['heavy lorry', 'crashed into the building']
Run Code Online (Sandbox Code Playgroud)