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

更新时间:2020-04-16    来源:python    手机版     字体:

【www.bbyears.com--python】

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-12. 比对两个配置文件的差异.
# 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

本文来源:http://www.bbyears.com/jiaocheng/92680.html

热门标签

更多>>

本类排行