difflib模块说明:
difflib模块是python中自带的模块,无需安装。作用是对比文本之间的差异,和Linux命令diff类似,但difflib支持输出可读性较高的HTML形式展示
先通过个小案例初步认识下怎么使用:
#!/usr/local/python3/bin/python3.6
import difflib
text1 = '''
Starry starry night
paint your palette blue and grey
look out on a summer's day
with eyes that know the darkness in my soul
Shadows on the hills
sketch the trees and daffodils
catch the breeze and the winter chills
in colors on the snowy linen land
'''
text2 = '''
Starry starry day by day
paint your palette blue and grey
look out on a summer's day
with eyes that know the darkness in my soul
Shadows on the hills
sketch the trees and daffodils
catch the breeze and the winter chills
in colors on the snowy linen land
'''
file1 = text1.splitlines()
file2 = text2.splitlines()
d = difflib.Differ() #创建Differ对象
result = d.compare(file1,file2) #采用compare方法对字符串进行比较,得到一个generator
print('\n'.join(list(result)))
得到的返回结果:
展示页面文本的不同,我们对展示输出的符号做下说明:
符号说明
-在第一个序列行中,但不在第二个序列行中
+在第二个序列行中,但不在第一个序列行中
''两个序列行一致
?标志出2个序列行存在增量差异
^标志出2个序列行存在的差异字符
命令行输出效果不是很直观,我们通过输出成HTML格式进行展示
#!/usr/local/python3/bin/python3.6
import difflib
text1 = '''
Starry starry night
paint your palette blue and grey
look out on a summer's day
with eyes that know the darkness in my soul
Shadows on the hills
sketch the trees and daffodils
catch the breeze and the winter chills
in colors on the snowy linen land
'''
text2 = '''
Starry starry day by day
paint your palette blue and grey
look out on a summer's day
with eyes that know the darkness in my soul
Shadows on the hills
sketch the trees and daffodils
catch the breeze and the winter chills
in colors on the snowy linen land
'''
file1 = text1.splitlines()
file2 = text2.splitlines()
d = difflib.HtmlDiff()
result = d.make_file(file1,file2)
print(result)
#输出从定向到文本中
python3.6 diff2.py >aa.html
difflib模块中方法说明:
import difflib #导入模块
d = difflib.Diff() #创建Diff对象
d.compare(file1,file2) #比较文本,得到generator
dd = difflib.HtmlDiff #HtmlDiff类可以实现HTML格式
dd.make_file(file1,file2) #实现对文本的比较
最后,我们看个实际案例:生产中我们会经常修改nginx的配置文件,太多次的修改导致我们无法确定文本的差异,通过该模块写个脚本可以明确的展示出文本间的差异性
import difflib
import sys
try:
args1 = sys.argv[1] #获取外部第一个参数
args2 = sys.argv[2] #获取外部的第二个参数
except Exception as e:
print("error:" + str(e))
sys.exit()
def read_file(file):
try:
with open(file) as rstream:
text = rstream.read().splitlines()
return text
except Exception as e:
print("error:file error" +str(e))
sys.exit()
if args1 =="" or args2 == "":
print("pls enter two file")
sys.exit()
test1 = read_file(args1)
test2 = read_file(args2)
d = difflib.HtmlDiff()
result = d.make_file(test1,test2)
print(result)
通过执行脚本, 输入2个参数(对比的文件),得到HTML文件,然后浏览器展示:
原文链接:https://blog.csdn.net/weixin_41910699/article/details/110114217