Infi-chu:
http://www.cnblogs.com/Infi-chu/
Module: Difflib
Installation: Python version greater than or equal to 2.3 system comes with
Function: Compare the differences between the text, and support the output of the more readable HTML document, and the diff command in Linux is similar.
Comparison of two string differences:
#import difflib#text1= "#hello World #how is. #nice to meet you.#" #text1_lines =text1.splitlines () # to split the line, Easy to compare #text2= ' #Hello world #how is you! #Nice to meet you~# "#text2_lines =text2.splitlines () # is split in rows for easy comparison #dif1= Difflib. Differ () # Create differ () object #diff1=dif1.compare (text1_lines,text2_lines) # Use the Compare () method to compare strings #print (' \ n '. Join (List ( DIFF1)))
Difflib also has the Sequencematcher () class, which supports comparisons of arbitrary types of sequences, as well as Htmldiff () classes, which support the output of comparison results in HTML format.
Symbol meaning Description:
Symbol
Meaning
‘-‘
Contained in the first sequence row, but not in the second sequence row
+
Contained in the second sequence row, but not in the first sequence line
‘ ‘
Two sequence lines consistent
‘?‘
Flag two sequence rows with delta differences
^
Flag the difference character that exists for two sequence lines
Generate HTML-formatted documents:
#import difflib#text1= "#hello World #how is. #nice to meet you.#" #text1_lines =text1.splitlines () # to split the line, Easy to compare #text2= ' #Hello world #how is you! #Nice to meet you~# "#text2_lines =text2.splitlines () # is split in rows for easy comparison #d= Difflib. Htmldiff () #print (D.make_file (Text1_lines,text2_lines)) # After making the resulting file into. html You can use the browser to view
Compare configuration file differences:
#import difflib#import os#try:# textfile1=sys.argv[1] # 1th configuration file Path parameter # textfile2=sys.argv[2] # 2nd profile Path parameter #except exception,e:# print (' Error: ' +str (e)) # print (' use: script name. py filename1 filename2 ') # sys.exit () #def ReadFile (filename): # File read delimited function # try:# filehandle=open (filename, ' RB ') # Text=filehandle.read (). Splitlines () # delimited by rows after reading # filehandle.close () # return text# except IOError as error:# print (' Read file error: ' +str (Error)) # sys.exit () #if textfile1== ' or textfile2== ': # print (' Use: script name. py filename1 filename2 ') # sys.exit () #text1_lines =readfile (textfile1) # call ReadFile get delimited string #text2_lines= ReadFile (textfile2) #d =difflib. Htmldiff () # Create HTMLDIFF () class object #print (D.make_file (text1_lines,text2_lines)) # Output HTML formatted results with the Make_file () method
Python automated operations--Comparison of file content differences