2

如何获得上下文差异(仅是有差异的行而不是所有行)以及使用 difflib.Differ() 比较行中的字符

例子

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

4

1 回答 1

2

显然,您可以过滤结果,删除以空格开头的行。列表理解和 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
?       ^
于 2014-07-11T04:20:15.333 回答