一、两个字符串的对比
1、两个字符串的对比输出
#!/bin/env python
import difflib
text1 = """text1:
This module provides classes and functions for comparing sequences v7.5"""
text1_lines = text1.splitlines()
text2 = """text2:
This module provides classes and functions for comparing sequences v7.4"""
text2_lines = text2.splitlines()
d = difflib.Differ()
diff = d.compare(text1_lines,text2_lines)
print ‘\n‘.join(list(diff))
本示例采用Differ()类对两个字符串进行比较,另外difflib的sequenceMatcher()类支持任意类型序列的比较,HtmlDiff()类支持将比较结果输出为HTML格式,示例运行结果如图2-1所示
2、生成美观的对比HTML格式文档
采用HtmlDiff()类的make_file()方法就可以生成美观的HTML文档,对示例1中代码按以下进行修改:
d = difflib.Differ()
diff = d.compare(text1_lines,text2_lines)
print ‘\n‘.join(list(diff))
替换成:
d = difflib.HtmlDiff()
print d.make_file(text1_lines,text2_lines)
将新文件命名为diff2.py。运行#python diff2.py,再使用浏览器打开diff.html文件,结果如果2-2所示,HTML文档包括了行号、差异标志、图例等信息,可读性增强了许多。
二、两个文件的对比
shell # vi diff3.py
#!/bin/env python
import difflib
import sys
try:
textfile1=sys.argv[1]
textfile2=sys.argv[2]
except Exception,e:
print "Error:"+str(e)
print "Usage: diff2.py filename1 filename2"
sys.exit()
def readfile(filename):
try:
fileHandle = open(filename, ‘rb‘)
text = fileHandle.read().splitlines()
fileHandle.close()
return text
except IOError as error:
print (‘Read file Error:‘+str(error))
sys.exit()
if textfile1=="" or textfile2=="":
print "Usage:diff3.py filename1 finename2"
sys.exit()
text1_lines = readfile(textfile1)
text2_lines = readfile(textfile2)
d = difflib.HtmlDiff()
print d.make_file(text1_lines,text2_lines)
从图2-3中可以看出diff.py和diff2.py的差别