difflib 模块包含一些用来计算和处理序列之间差异的工具。它对于比较文本尤其有用,其中包含的函数可以使用多种常用差异格式生成报告。
实现了三个类:
-
SequenceMatcher 任意类型序列的比较 (可以比较字符串)
-
Differ 对字符串进行比较
-
HtmlDiff 将比较结果输出为html格式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
#!/usr/bin/env python
#
#-*- coding: utf-8 -*-
import
difflib
import
sys
try:
textfile1=sys.argv[1]
textfile2=sys.argv[2]
except Exception as e:
print(
"Error:"
+str(e))
print(
"Usage:diff_Simple3.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:diff_Simple3"
)
sys.
exit
()
text1_lines=readfile(textfile1)
text2_lines=readfile(textfile2)
d = difflib.HtmlDiff()
print(d.make_file(text1_lines,text2_lines))
|
本文转自 SoulMio 51CTO博客,原文链接:http://blog.51cto.com/bovin/1940971,如需转载请自行联系原作者