Overview
• The get_matching_blocks() method of the SequenceMatcher class returns the starting index and the length of each matching block from two sequences that are non-overlapping.
• The details of the matching blocks are returned as a list of tuples.
Example
# Example Python program that returns the matching
# blocks that are not overlapping from the two given sequences
import difflib
# Create a SequenceMatcher object
seqMatcher = difflib.SequenceMatcher()
# Set sequence1
seq1 = "Then while we live, in love let’s so persever,"
seqMatcher.set_seq1(seq1)
# Set sequence2
seq2 = "That when we live no more we may live ever."
seqMatcher.set_seq2(seq2)
# Find the matching blocks
matches = seqMatcher.get_matching_blocks()
print(matches)
print(type(matches))
print("Sequence one:")
print(seq1)
print("Sequence two:")
print(seq2)
print("Matching non-overlapping sub-sequences:")
for match in matches:
print(seq1[match.a:match.a + match.size])
print(seq2[match.b:match.b + match.size])Output
[Match(a=0, b=0, size=1), Match(a=1, b=6, size=3), Match(a=10, b=9, size=8), Match(a=19, b=17, size=1), Match(a=21, b=18, size=1), Match(a=22, b=32, size=2), Match(a=25, b=35, size=3), Match(a=41, b=38, size=4), Match(a=46, b=43, size=0)]
<class 'list'>
Sequence one:
Then while we live, in love let’s so persever,
Sequence two:
That when we live no more we may live ever.
Matching non-overlapping subsequences:
T
T
hen
hen
we live
we live
n
n
l
l
ve
ve
ever
ever