首页 > 编程语言 > 详细

Python笔记(23)-difflib模块

时间:2019-07-16 23:37:04      阅读:99      评论:0      收藏:0      [点我收藏+]

文件差异对比

示例一:

#coding:utf-8import 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(1)

 

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.‘‘‘.splitlines(1)
# 创建diff对象

d=difflib.Differ()
# 采用compare方法对字符串进行比较for i in d.compare(text1,text2):

    print i

执行结果:

 技术分享图片

 

import difflib

text1 = ‘hello westos‘

text2 = ‘hello zhan‘

text1_lines = text1.splitlines()

text2_lines = text2.splitlines()# 创建diff对象

d = difflib.Differ()# 采用compare方法对字符串进行比较

diff = d.compare(text1_lines, text2_lines)# print list(diff)print ‘\n‘.join(list(diff))

参数:

‘-‘ 包含在第一个中,但不包含在第二个中
‘+‘ 包含在第二个中,但不包含在第一个中
‘‘ 两者相同
‘?‘ 两个存在增量差异
‘^‘ 标志出两者行存在的差异字符

示例二:

#coding:utf-8import 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(1)

 

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.‘‘‘.splitlines(1)

d=difflib.HtmlDiff()print d.make_file(text1,text2)

执行结果:

[vaon@station Desktop]$ python diff_file.py >/home/vaon/Desktop/diff_file.html

执行完之后桌面上会生成一个html文件,用浏览器打开就可以直观的看到两个文件的不同:

 技术分享图片

 

Python笔记(23)-difflib模块

原文:https://www.cnblogs.com/vaon/p/11198251.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!