Python Difflib Module
The difflib module provides classes and functions for comparing sequences. It can be used for example, for comparing files, and can produce difference information in various formats, including HTML and context and unified diffs.
Importing the Module
import difflib
Comparing Sequences
SequenceMatcher
This is a flexible class for comparing pairs of sequences of any type, so long as the sequence elements are hashable.
import difflib
s1 = "Apple"
s2 = "Appel"
matcher = difflib.SequenceMatcher(None, s1, s2)
print(f"Ratio: {matcher.ratio()}") # Output: 0.8
You can also get detailed opcodes describing how to turn s1 into s2.
for tag, i1, i2, j1, j2 in matcher.get_opcodes():
print(f"{tag:7} a[{i1}:{i2}] ({s1[i1:i2]}) b[{j1}:{j2}] ({s2[j1:j2]})")
Finding Close Matches
The get_close_matches() function returns a list of the best "good enough" matches.
import difflib
words = ['apple', 'ape', 'application', 'peach', 'puppy']
matches = difflib.get_close_matches('appel', words)
print(matches)
# Output: ['apple', 'ape']
Generating Diffs
Differ
The Differ class is used for comparing sequences of lines of text, and producing human-readable differences or deltas.
import difflib
text1 = """line 1
line 2
line 3""".splitlines(keepends=True)
text2 = """line 1
line 2 changed
line 3""".splitlines(keepends=True)
d = difflib.Differ()
diff = d.compare(text1, text2)
print(''.join(diff))
unified_diff
For a more compact diff (like the diff command line tool), use unified_diff().
import difflib
diff = difflib.unified_diff(text1, text2, fromfile='file1', tofile='file2')
print(''.join(diff))
HtmlDiff
This class can be used to create an HTML table (or a complete HTML file) showing a side by side, line by line comparison of text with inter-line and intra-line change highlights.
import difflib
d = difflib.HtmlDiff()
html = d.make_file(text1, text2)
# with open('diff.html', 'w') as f:
# f.write(html)