Reputation: 3166
How can I get contextual difference (e.i only the lines with difference and not all lines) along with comparing the characters within a Line using difflib.Differ()
Example
>>> text1 = ''' 1. 111
... 2. 222
... 3. 333
... 4. 444
... '''.splitlines(1)
>>> text2 = ''' 1. 121 xxx
... 2. 222
... 3. 313
... 4. 444
... '''.splitlines(1)
>>> from difflib import Differ
>>> d = Differ()
>>>
>>> print ''.join(d.compare(text1, text2))
- 1. 111
+ 1. 121 xxx
2. 222
- 3. 333
? ^
+ 3. 313
? ^
4. 444
>>>
# I want something like this with context=True
>>> print ''.join(d.compare(text1, text2))
- 1. 111
+ 1. 121 xxx
- 3. 333
? ^
+ 3. 313
? ^
UPDATE: I have answered it here: python difflib character diff with unifed contextual format
Upvotes: 2
Views: 4949
Reputation: 34136
Obviously you can filter the results, removing lines that start with whitespace. A list comprehension and str.startswith can do that.
>>> from difflib import Differ
>>> d = Differ()
>>> print ''.join(line for line in d.compare(text1, text2) if not line.startswith(' '))
- 1. 111
+ 1. 121 xxx
- 3. 333
? ^
+ 3. 313
? ^
Upvotes: 3