difflib是python提供的比较序列(string list)差异的模块。实现了三个类:
1>SequenceMatcher 任意类型序列的比较 (可以比较字符串)
2>Differ 对字符串进行比较
3>HtmlDiff 将比较结果输出为html格式.
SequenceMatcher实例:
import difflib from pprint import pprint a = 'pythonclub.org is wonderful' b = 'Pythonclub.org also wonderful' s = difflib.SequenceMatcher(None, a, b) print "s.get_matching_blocks():" pprint(s.get_matching_blocks()) print "s.get_opcodes():" for tag, i1, i2, j1, j2 in s.get_opcodes(): print ("%7s a[%d:%d] (%s) b[%d:%d] (%s)" % (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2])) |
输出为:
s.get_matching_blocks(): [(1, 1, 14), (16, 17, 1), (17, 19, 10), (27, 29, 0)] s.get_opcodes(): |
SequeceMatcher(None,a,b)创建序列比较对象,将以a作为参考标准进行
Sequecematcher(None,b,a)创建序列比较对象,将以b作为参考标准进行
a,b表示待比较的两个序列,生成序列比较对象后,调用该对象的get_opcodes()方法,将返回一个元组(tag,i1,i2,j1,j2).tag表示序列分片的比较结果.i1,i2表示序列a的索引,j1,j2表示序列b的索引.
get_opcodes()返回元组(tag,i1,i2,j1,j2)的含义
tag值 | 处理过程 |
Replace | a[i1,i2]被b[j1,j2]替换 |
Delete | a[i1,i2]分片被删除,此时j1等会j2 |
Insert | b[j1.j2]插入到a[i1,i2]位置处,此时的i1等会i2 |
Equal | a[i1,i2]等于b[j1,j2] |
Differ实例:
>>> import difflib >>> diff = difflib.Differ().compare("start up","starT u4p") >>> print "/n".join(list(diff)) s t a r - t + T u + 4 p |
HtmlDiff实例:
from difflib import * s = HtmlDiff.make_file(HtmlDiff(),"start up","storT up") f=open(r"/root/xukai.html","w") f.write(s) f.close |