具有上下文差异的Python difflib.Differ

时间:2014-07-11 04:09:51

标签: python difflib

如何使用difflib.Differ()

获取上下文差异(e.i只有差异而不是所有行的行)以及比较行内的字符

实施例

>>> 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
?       ^

更新 我在这里回答:python difflib character diff with unifed contextual format

1 个答案:

答案 0 :(得分:1)

显然,您可以过滤结果,删除以空格开头的行。列表理解和str.startswith可以做到这一点。

>>> 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
?       ^