2

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

1 Answer 1

3

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
?       ^
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.