欢迎访问www.showerlee.com, 您的支持就是我前进的动力.

[Python] 利用HTML页面查看字符串差异

showerlee 2015-09-28 16:21 LAN, PYTHON 阅读 (1,510) 抢沙发

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

浏览器打开该页面

如图:

QQ20150928-1

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

QQ20150929-1

正文部分到此结束
版权声明:除非注明,本文由(showerlee)原创,转载请保留文章出处!
本文链接:http://www.showerlee.com/archives/1580

继续浏览:

还没有评论,快来抢沙发!

发表评论

icon_wink.gif icon_neutral.gif icon_mad.gif icon_twisted.gif icon_smile.gif icon_eek.gif icon_sad.gif icon_rolleyes.gif icon_razz.gif icon_redface.gif icon_surprised.gif icon_mrgreen.gif icon_lol.gif icon_idea.gif icon_biggrin.gif icon_evil.gif icon_cry.gif icon_cool.gif icon_arrow.gif icon_confused.gif icon_question.gif icon_exclaim.gif