Created
October 21, 2011 20:24
-
-
Save rsbohn/1304857 to your computer and use it in GitHub Desktop.
show differences in strings -- uses SequenceMatcher
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from difflib import SequenceMatcher | |
def diff(actual, expected): | |
if actual != expected: | |
raise AssertionError(combine(actual, expected)) | |
def combine(a,b): | |
"""Form one string showing the differences between a and b.""" | |
sm = SequenceMatcher(None, a,b) | |
out = [] | |
for op in sm.get_opcodes(): | |
if op[0] == 'equal': | |
out.append(sm.a[op[1]:op[2]]) | |
else: | |
out.append("("+sm.a[op[1]:op[2]]+"|"+sm.b[op[3]:op[4]]+")") | |
return ''.join(out) | |
aa="Beware the angry badger with a cudgel" | |
ab="Beware any badger with a stout cudgel" | |
# sample output: | |
# Beware (the |)an(gr|)y badger with a (|stout )cudgel | |
if __name__ == '__main__': | |
print combine(aa,ab) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment