python difflib模块详解


当前第2页 返回上一页

示例


1

2

3

4

5

6

7

8

9

10

11

>>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1),

...       'ore\ntree\nemu\n'.splitlines(1))

>>> diff = list(diff) # materialize the generated delta into a list

>>> print ''.join(restore(diff, 1)),

one

two

three

>>> print ''.join(restore(diff, 2)),

ore

tree

emu

difflib.unified_diff(a, b[, fromfile][, tofile][, fromfiledate][, tofiledate][, n][, lineterm])

比较a与b(字符串列表),返回一个unified diff格式的差异结果.

示例:


1

2

3

4

5

6

7

8

9

10

11

12

13

14

>>> s1 = ['bacon\n', 'eggs\n', 'ham\n', 'guido\n']

>>> s2 = ['python\n', 'eggy\n', 'hamster\n', 'guido\n']

>>> for line in unified_diff(s1, s2, fromfile='before.py', tofile='after.py'):

...  sys.stdout.write(line)

--- before.py

+++ after.py

@@ -1,4 +1,4 @@

-bacon

-eggs

-ham

+python

+eggy

+hamster

 guido

实际应用示例

比对两个文件,然后生成一个展示差异结果的HTML文件


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

#coding:utf-8

'''

file:difflibeg.py

date:2017/9/9 10:33

author:lockey

email:lockey@123.com

desc:diffle module learning and practising

'''

import difflib

hd = difflib.HtmlDiff()

loads = ''

with open('G:/python/note/day09/0907code/hostinfo/cpu.py','r') as load:

 loads = load.readlines()

 load.close()

 

mems = ''

with open('G:/python/note/day09/0907code/hostinfo/mem.py', 'r') as mem:

 mems = mem.readlines()

 mem.close()

 

with open('htmlout.html','a+') as fo:

 fo.write(hd.make_file(loads,mems))

 fo.close()

运行结果:

这里写图片描述

生成的html文件比对结果:

这里写图片描述

以上就是python difflib模块详解的详细内容,更多文章请关注木庄网络博客!!

返回前面的内容

相关阅读 >>

Python 列表推导式使用注意事项

了解Python的collections.counter类型

读懂Python的异常机制

Python列表和元组的相同点和不同点是什么

pip Python库安装在哪里了

a[1:]在Python什么意思

在不同的Python版本中,不换行输出有什么变化?

Python比较两浮点数是否相等的方法

详谈Python在windows中的文件路径问题

Python调用xlsxwriter创建xlsx的方法

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...