Python2.3以上的版本自带difflib模块,无需安装
示例:两个字符串的差异对比
"""
两个字符串的差异对比
"""
import difflib
text1="""text1:
This module provides classes and functions for comparing sequences.
including HTML and context and unified diffs.
difflib document v7.4
add string
"""
text1_lines = text1.splitlines() #以行进行分隔,以便进行对比
text2="""text2:
This module provides classes and functions for Comparing sequences.
including HTML and context and unified diffs.
difflib document v7.5"""
text2_lines = text2.splitlines()
d = difflib.Differ() #创建Differ对象
diff = d.compare(text1_lines,text2_lines) #采用compare方法对字符串进行比较
print('\n'.join(list(diff)))
运行结果:
[root@foundation8 autopy]# /usr/local/python3.6/bin/python3.6 difflib-1.py
- text1:
? ^
+ text2:
? ^
- This module provides classes and functions for comparing sequences.
? ^
+ This module provides classes and functions for Comparing sequences.
? ^
including HTML and context and unified diffs.
- difflib document v7.4
? ^
+ difflib document v7.5
? ^
- add string
'-' 包含在第一个序列行中,但不包含在第二个序列行中
'+' 包含在第二个序列行中,但不包含在第一个序列行中
'' 两个序列行一致
'?' 标志两个序列行存在增量差异
'^' 两个序列行存在差异的字符
对比结果生成HTML文档
刚才对比生成的结果不是很美观,所以接下来我们将生成HTML文档的格式,然后在浏览器中进行查看
"""
两个字符串的差异对比
生成HTML文档的格式
"""
import difflib
text1="""text1:
This module provides classes and functions for comparing sequences.
including HTML and context and unified diffs.
difflib document v7.4
add string
"""
text1_lines = text1.splitlines()
text2="""text2:
This module provides classes and functions for Comparing sequences.
including HTML and context and unified diffs.
difflib document v7.5"""
text2_lines = text2.splitlines()
d = difflib.HtmlDiff()
print(d.make_file(text1_lines,text2_lines))
运行:
[root@foundation8 autopy]# /usr/local/python3.6/bin/python3.6 difflib-HTML.py > /var/www/html/diff.html
浏览器查看:
对比Nginx配置文件差异
当我们维护多个Nginx配置时,时常会对比不同版本配置文件的差异,使运维人员更加直观地了解不同版本的区别。具体实现思路是读取两个需对比的配置文件,再以换行符作为分隔符,调用difflib.HtmlDiff()生成HTML格式的差异文档。代码如下:
import difflib
import sys
textfile1 = sys.argv[1]
textfile2 = sys.argv[2]
def readfile(filename):
fileHandle = open (filename,'r')
text = fileHandle.read().splitlines()
fileHandle.close()
return text
text1_lines = readfile(textfile1)
text2_lines = readfile(textfile2)
d = difflib.HtmlDiff()
print(d.make_file(text1_lines,text2_lines))
~
运行:
[root@foundation8 autopy]# /usr/local/python3.6/bin/python3.6 difflib_nginx.py nginx.conf.v1.10.1 nginx.conf.v1.15.7 > /var/www/html/diff.html
浏览器查看: