python中的difflib

2023-01-31 02:01:45 python difflib


#############difflib##############

文件差异对比

示例1:

import difflib

text1 = 'hello westos'

text2 = 'hello zhan'

text1_lines = text1.splitlines()

text2_lines = text2.splitlines()

# 创建diff对象

d = difflib.Differ()

# 采用compare方法对字符串进行比较

diff = d.compare(text1_lines, text2_lines)

# print list(diff)

print '\n'.join(list(diff))

 

 

text1='''root:x:0:wfew0:root:/root:/bin/bash

bin:x:1fw:1:bin:/bin:/sbwefwin/nologin

daemon:xw:2:2:daefwmon:/sbin:/sbin/nologin

adm:x:3:4:adwfwfm:/var/adm:/sbin/nologin

lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin

synsfwfsc:x:5:0:sync:/sbin:/bin/sync

shautdowfwfwn:x:6:0:shutdown:/sbin:/sbin/shutdown

halt:x:7:0:halt:/sbin:/sbin/halt

'''

text2='''rot:x:0:0:root:/root:/bin/bash

bin:x:1:1:bi:/bin:/sbin/nologindaem

on:x:2:2:daemon:/sbin:/sbin/login

adm:x:3:4:adm:var/adm:/sbin/nolog

lp:x:4:7:lp:/var/spool/lpd:/sbin/nolo

GISync:x:5:0:sync:/sbin:/bin/sync

utdown:x:6:0:shtdown:/sbin:/sbin/shutdown

halt:x:7:0:halt:/sbin:/sbin/halt

'''

第一种方法

import difflib

text1_lines=text1.splitlines()

text2_lines=text2.splitlines()

d=difflib.Differ()

a=d.compare(text1_lines,text2_lines)

a=list(a)

print '\n'.join(a)

 

测试

 wKiom1ls6IuQ0FR_AAA8yMlrvS0845.png-wh_50

第二种方法

import difflib

text1_lines=text1.splitlines()

text2_lines=text2.splitlines()

# d=difflib.Differ()

# a=d.compare(text1_lines,text2_lines)

# a=list(a)

# print '\n'.join(a)

d=difflib.htmlDiff()

htmldata=d.make_file(text1_lines,text2_lines)

with open('/root/Desktop/data.html','a+') as f:

    f.write(htmldata)

 

 

测试:

 wKioL1ls6JjQpzE_AAD173e4ol4979.png-wh_50

 

文件差异对比

'-' 包含在第一个中,但不包含在第二个中

'+' 包含在第二个中,但不包含在第一个中

' ' 两者相同

'?' 两个存在增量差异

'^' 标志出两者行存在的差异字符


 


相关文章