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中socket实现tcp通信的介绍(附示例)

Python中n是什么意思?

Python怎么表示八进制

Python print用法详解

盘点Python中断多重循环的思路

Python如何实现格式化输出

Python怎么输入一个三位数,输出百位、十位和个位

Python以太坊虚拟机实现py-evm的内容介绍

Python实现从字典中提取子集的方法(代码)

Python访问限制私有还是公有的介绍(附示例)

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




打赏

取消

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

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

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

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

评论

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