Python automatic operation and maintenance -- file content difference comparison

Infi-chu:

http://www.cnblogs.com/Infi-chu/

Module: difflib

Installation: Python version greater than or equal to 2.3

Function: compare the differences between texts, and support the output of HTML documents with strong readability, which is similar to the diff command in Linux.

Difference comparison between two strings:

#import difflib

#text1='''

#hello world.

#how are you.

#nice to meet you.

#'''

#text1_lines=text1.splitlines() # Split by lines for comparison

#text2='''

#Hello World.

#how are you!

#Nice to meet you~

#'''

#text2_lines=text2.splitlines() # Split by lines for comparison

#dif1=difflib.Differ() # Create a Differ() object

#diff1=dif1.compare(text1_lines,text2_lines) # Compare strings with compare() method

#print('\n'.join(list(diff1)))

In addition, difflib has SequenceMatcher() class, which supports comparison of any type of sequence; and HtmlDiff() class, which supports output of comparison results in HTML format.

Symbol meaning Description:

Symbol

meaning

'-'

Included in first sequence line, but not in second sequence line

'+'

Included in the second sequence line, but not in the first sequence line

' '

Two sequence lines are consistent

'?'

Mark incremental difference between two sequence lines

'^'

Mark the difference between two sequence lines

To generate an HTML document:

#import difflib

#text1='''

#hello world.

#how are you.

#nice to meet you.

#'''

#text1_lines=text1.splitlines() # Split by lines for comparison

#text2='''

#Hello World.

#how are you!

#Nice to meet you~

#'''

#text2_lines=text2.splitlines() # Split by lines for comparison

#d=difflib.HtmlDiff()

#print(d.make_file(text1_lines,text2_lines))

# After that, the generated file can be changed to. html, which can be viewed by browser

Compare profile differences:

#import difflib

#import os

#try:

# textfile1=sys.argv[1] # 1st profile 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 separator function

# try:

# fileHandle=open(filename,'rb')

# text=fileHandle.read().splitlines() # Separate by row after reading

# fileHandle.close()

# return text

# except IOError as error:

# print('error reading file: '+ str(error))

# sys.exit()

#if textfile1=='or textfile2==':

# print('use: script name. py filename1 filename2 ')

# sys.exit()

#text1_lines=readfile(textfile1) # Call readfile to get the separated string

#text2_lines=readfile(textfile2)

#d=difflib.HtmlDiff() # Create an HtmlDiff() class object

#print(d.make_file(text1_lines,text2_lines)) # Through make_ The file () method outputs the result in HTML format

Tags: Python Linux

Posted on Sun, 31 May 2020 12:51:28 -0400 by anne13