difflib模块

 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 
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():
replace a[0:1] (p) b[0:1] (P)
  equal a[1:15] (ythonclub.org ) b[1:15] (ythonclub.org )
replace a[15:16] (i) b[15:17] (al)
  equal a[16:17] (s) b[17:18] (s)
 insert a[17:17] () b[18:19] (o)
  equal a[17:27] ( wonderful) b[19:29] ( wonderful)

 

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

 

在页面访问xukai.html,效果如下图:

[python] difflib模块 - 徐开 - xukaizijian

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值