一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

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

时间:2016-01-25 编辑:简简单单 来源:一聚教程网

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-1javascript:this.src='/get_pic/2016/01/25/201601251336401.jpg'" size-large="" src="https://img.111com.net/get_pic/2016/01/25/20160125133642792.png" />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

热门栏目