SequenceMatcher Opcodes Build Word Diffs

Run SequenceMatcher.get_opcodes over word lists to get equal, replace, delete, and insert ranges, so a diff describes sentence edits instead of whole lines.

PythonData Integrity

Code

pythonsnippet
20 lines
import difflib

old = 'the deploy finished without any error today'
new = 'the deploy finished without a single error today'

# Split into words first, so opcodes describe sentence edits
# instead of whole-line replacements
old_words = old.split()
new_words = new.split()
matcher = difflib.SequenceMatcher(None, old_words, new_words)

for tag, i1, i2, j1, j2 in matcher.get_opcodes():
    if tag == 'equal':
        print(f'keep   {old_words[i1:i2]}')
    elif tag == 'replace':
        print(f'swap   {old_words[i1:i2]} -> {new_words[j1:j2]}')
    elif tag == 'delete':
        print(f'drop   {old_words[i1:i2]}')
    else:
        print(f'insert {new_words[j1:j2]}')

How it works

Repetition is confined to for tag, i1, i2, j1, j2 in matcher.get_opcodes() — the rest of the file is straight-line.

Everything operates on top-level bindings: old, new, old_words, new_words.

Watch out for

  • Runs on the standard library alone; nothing to install.

Using it

The run emits 4 labeled sections — keep, swap, drop, insert — one per step.

Key statements worth quoting

elif tag == 'replace':
    print(f'swap   {old_words[i1:i2]} -> {new_words[j1:j2]}')
elif tag == 'delete':
    print(f'drop   {old_words[i1:i2]}')

Interactive Tools for This Topic

FAQ

Can I paste this into a project as-is?
Yes. Paste it in and run; no package manager step is needed. Every import resolves inside the standard library — `difflib`. Its state lives in module-level bindings: `old`, `new`, `old_words`.