When comparing similar lines, I want to highlight the differences on the same line:
JavaScript
x
5
1
a) lorem ipsum dolor sit amet
2
b) lorem foo ipsum dolor amet
3
4
lorem <ins>foo</ins> ipsum dolor <del>sit</del> amet
5
While difflib.HtmlDiff appears to do this sort of inline highlighting, it produces very verbose markup.
Unfortunately, I have not been able to find another class/method which does not operate on a line-by-line basis.
Am I missing anything? Any pointers would be appreciated!
Advertisement
Answer
For your simple example:
JavaScript
1
22
22
1
import difflib
2
def show_diff(seqm):
3
"""Unify operations between two compared strings
4
seqm is a difflib.SequenceMatcher instance whose a & b are strings"""
5
output= []
6
for opcode, a0, a1, b0, b1 in seqm.get_opcodes():
7
if opcode == 'equal':
8
output.append(seqm.a[a0:a1])
9
elif opcode == 'insert':
10
output.append("<ins>" + seqm.b[b0:b1] + "</ins>")
11
elif opcode == 'delete':
12
output.append("<del>" + seqm.a[a0:a1] + "</del>")
13
elif opcode == 'replace':
14
raise NotImplementedError("what to do with 'replace' opcode?")
15
else:
16
raise RuntimeError("unexpected opcode")
17
return ''.join(output)
18
19
>>> sm= difflib.SequenceMatcher(None, "lorem ipsum dolor sit amet", "lorem foo ipsum dolor amet")
20
>>> show_diff(sm)
21
'lorem<ins> foo</ins> ipsum dolor <del>sit </del>amet'
22
This works with strings. You should decide what to do with “replace” opcodes.