Skip to content

Instantly share code, notes, and snippets.

@napsternxg
Last active January 12, 2022 18:33
Show Gist options
  • Save napsternxg/ea7aa5b133709d608b35a248c2c5000a to your computer and use it in GitHub Desktop.
Save napsternxg/ea7aa5b133709d608b35a248c2c5000a to your computer and use it in GitHub Desktop.
Python difflib for string diffs
# Using python difflib
from difflib import Differ, ndiff, SequenceMatcher, HtmlDiff
from pprint import pprint
from IPython.display import display_html, HTML, display
css_style = """
<style>
del {
text-decoration: line-through;
background-color: #fbb;
color: #555;
}
ins {
text-decoration: none;
background-color: #d4fcbc;
}
</style>
"""
def show_diff(a, b):
s = SequenceMatcher(None, a, b)
unified_diff = ["<p>"]
for tag, i1, i2, j1, j2 in s.get_opcodes():
# print('{:7} a[{}:{}] --> b[{}:{}] {!r:>8} --> {!r}'.format(tag, i1, i2, j1, j2, a[i1:i2], b[j1:j2]))
if tag == "equal":
unified_diff.append(a[i1:i2])
else:
unified_diff.append(f"<del>{a[i1:i2]}</del>")
unified_diff.append(f"<ins>{b[j1:j2]}</ins>")
unified_diff.append("</p>")
unified_diff = "".join(unified_diff).replace("\n", "<br/>")
return HTML(f"{css_style}\n{unified_diff}")
a, b, = 'one\ntwo\nthree\n', 'ore\ntree\nemu\n'
show_diff(a, b)
# HTML Table of Diff
d = HtmlDiff()
display(HTML(d.make_table('one\ntwo\nthree\n'.splitlines(keepends=True),
'ore\ntree\nemu\n'.splitlines(keepends=True))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment