Python(十七)difflib模块

一、模块的功能

    主要是用来进行序列的差异化比较,它能够比对文件并生成差异结果文本或者html格式的差异化比较页面!

    换句话说:生成比linux中diff更人性化的文件差异比较!

二、练习

练习1:体会splitlines的作用

# 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.
        '''.splitlines(keepends=False)
print(text1)
print(text2

# 返回一个列表(各元素为每行的元素)

需求2:实现linux里面类似diff命令的功能

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.
        '''.splitlines(keepends=True)
# keepends=True的含义是保留\n,(一般保留\n)
# 理解官方内置的第三方模块和内置进环境的模块!
d = difflib.Differ()
# print(list(d.compare(text1,text2)))
# 说明:由于保留空格,所以这里打印 不是连成一行
print(''.join(list(d.compare(text1, text2))))

############################################

# 说明:以html页面的形式展示差异性
d = difflib.HtmlDiff()
# 说明:html的内容
htmlContent = d.make_file(text1, text2)
# print(htmlContent)

练习2:将生成的差异性文件制作成html页面

# 保存到文件中,以浏览器打开
import difflib

filename1='/tmp/passwd'
filename2='/tmp/passwd1'

#(1)生成html页面的内容
with open(filename1) as f1,open(filename2) as f2:
    content1=f1.read().splitlines(keepends=True)
    content2=f2.read().splitlines(keepends=True)
d=difflib.HtmlDiff()
htmlContent=d.make_file(content1,content2)

#(2)生成html格式的文件
with open('passwdDiff.html','w') as file:
    file.write(htmlContent)

# 涉及html页面的生成,以及文件的读写!

说明:本章节不讲解相关的类与方法,如有需要可以参考相关链接、链接2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值