On this page
difflib.SequenceMatcher
Prev: difflib.restore | Up: difflib | Next: difflib.unified_diff
Rel: difflib.context_diff, difflib.diff_bytes, difflib.Differ, difflib.get_close_matches
Ref: docs.python.org — difflib.SequenceMatcher
Tags: #public #python3 #stdlib #difflib
Import
import difflib
from difflib import SequenceMatcher
Signature & Overview
difflib.SequenceMatcher(isjunk=None, a='', b='', autojunk=True)
SequenceMatcher is a flexible class for comparing pairs of sequences of any type, so long as the sequence elements are hashable. The basic algorithm predates, and is a little fancier than, an algorithm
Methods & Attributes
SequenceMatcher.find_longest_match(self, alo=0, ahi=None, blo=0, bhi=None)— Find longest matching block in a[alo:ahi] and b[blo:bhi].SequenceMatcher.get_grouped_opcodes(self, n=3)— Isolate change clusters by eliminating ranges with no changes.SequenceMatcher.get_matching_blocks(self)— Return list of triples describing matching subsequences.SequenceMatcher.get_opcodes(self)— Return list of 5-tuples describing how to turn a into b.SequenceMatcher.quick_ratio(self)— Return an upper bound on ratio() relatively quickly.SequenceMatcher.ratio(self)— Return a measure of the sequences' similarity (float in [0,1]).SequenceMatcher.real_quick_ratio(self)— Return an upper bound on ratio() very quickly.SequenceMatcher.set_seq1(self, a)— Set the first sequence to be compared.SequenceMatcher.set_seq2(self, b)— Set the second sequence to be compared.SequenceMatcher.set_seqs(self, a, b)— Set the two sequences to be compared.
Usage
import difflib
sm = difflib.SequenceMatcher(None, "kitten", "sitting")
assert 0.5 < sm.ratio() < 0.7
assert any(tag == "replace" for tag, *_ in sm.get_opcodes())
Gotchas
- Disable
autojunk=Falsefor exact diffs on long sequences: By default (autojunk=True), repeated elements (>1% of a 200+ item sequence) are treated as junk to speed up matching.
REPL Inspect
from difflib import SequenceMatcher
help(SequenceMatcher)
Linked from
Related notes
- tuts/python3/stdlib_module/difflib/restore Linked here; links to this page; shared tags: #difflib, #stdlib
- tuts/python3/stdlib_module/difflib/unified_diff Linked here; links to this page; shared tags: #difflib, #stdlib
- tuts/python3/stdlib_module/difflib Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/difflib/context_diff Linked here; shared tags: #difflib, #stdlib
- tuts/python3/stdlib_module/difflib/diff_bytes Linked here; shared tags: #difflib, #stdlib
- tuts/python3/stdlib_module/difflib/Differ Linked here; shared tags: #difflib, #stdlib
- tuts/python3/stdlib_module/difflib/get_close_matches Linked here; shared tags: #difflib, #stdlib
- tuts/python3/stdlib_module/difflib/HtmlDiff shared tags: #difflib, #stdlib
- tuts/python3/stdlib_module/difflib/Match shared tags: #difflib, #stdlib
- tuts/python3/stdlib_module/difflib/ndiff shared tags: #difflib, #stdlib