只想简单地比较一下文本之间是否有变化,就可以函数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 深圳