python文本字符串比对_[Python] 利用HTML页面查看字符串差异

1. 比对两个字符串差异.

# vi diff.py

#!/usr/bin/env python

import difflib

text1 = '''text1:

This mudule provides classes and fuctions for comparing sequences.

including HTML and context and unified diffs.

difflib document v7.4

add string

'''

text1_lines = text1.splitlines()

text2 = '''text2:

This mudule provides classes and fuctions for Comparing sequences.

including HTML and context and unified diffs.

difflib document v7.5

'''

text2_lines = text2.splitlines()

#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)

运行脚本并重定向为一个html静态页面

# chmod 755 diff.py

# ./diff.py  > diff.html

浏览器打开该页面

如图:

2. 比对两个配置文件的差异.

# vi diff02.py

#!/usr/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: %s filename1 filename2" %sys.argv[0]

sys.exit()

def readfile(filename):

try:

with open(filename, 'rb') as fileHandle:

text = fileHandle.read().splitlines()

return text

except IOError as error:

print ('Read file Error:' + str(error))

sys.exit()

if not textfile1 or not textfile2:

print "Usage: %s filename1 filename2" %sys.argv[0]

sys.exit()

text1_lines = readfile(textfile1)

text2_lines = readfile(textfile2)

d = difflib.HtmlDiff()

print d.make_file(text1_lines, text2_lines)

# ./diff02.py nginx.conf.v1 nginx.conf.v2 >diff02.html

正文部分到此结束

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值