您的位置:首页 > 其它

3.3.6 使用difflib.context_diff函数

2015-09-28 11:28 288 查看
只想简单地比较一下文本之间是否有变化,就可以函数defflib.context_diff来实现。

例子:

#python3.4.3

import difflib

text1 = '''  1. Beautiful is better than ugly.
2. Explicit is better than implicit.
3. Simple is better than complex.
4. Complex is better than complicated.
'''.splitlines(keepends=True)

text2 = '''  1. Beautiful is better than ugly.
3.   Simple is better than complex.
4. Complicated is better than complex.
5. Flat is better than nested.
0. test
'''.splitlines(keepends=True)

for line in difflib.context_diff(text1, text2, 'fromfile', 'tofile',
'fromfiledate', 'tofiledate', 1, '\n'):
print(line)


结果输出如下:

*** fromfile fromfiledate

--- tofile tofiledate

***************

*** 1,5 ****

1. Beautiful is better than ugly.

! 2. Explicit is better than implicit.

! 3. Simple is better than complex.

! 4. Complex is better than complicated.

--- 1,6 ----

1. Beautiful is better than ugly.

! 3. Simple is better than complex.

! 4. Complicated is better than complex.

! 5. Flat is better than nested.

! 0. test

在每行头有!的,就表示此行已经作出改变。

蔡军生 微信号:shenzhencai 深圳
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: