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))
输出:
['heavy lorry', 'crashed into the building']