天天看點

python中的diff有什麼作用_python中difflib内置子產品之文本對比

什麼是difflib? 用來做什麼?

difflib為python的标準庫子產品,無需安裝。

作用時對比文本之間的差異。

并且支援輸出可讀性比較強的HTML文檔,與Linux下的diff 指令相似。

在版本控制方面非常有用。

符号了解

符号 含義

‘-‘ 包含在第一個系列行中,但不包含第二個。

‘+‘ 包含在第二個系列行中,但不包含第一個。

‘ ‘ 兩個系列行一緻

‘?‘ 存在增量差異

‘^‘ 存在差異字元

import difflib

text1 = ‘‘‘ 1. Beautiful is better than ugly.

Explicit is better than implicit.

Simple is better than complex.

Complex is better than complicated.

‘‘‘.splitlines(keepends=False)

print(text1) 将多行文本按行分隔,傳回一個清單,不保留行尾換行符

text2 = ‘‘‘ 1. Beautiful is better than ugly.

Simple is better than complex.

Complicated is better than complex.

Flat is better than nested.

‘‘‘.splitlines(keepends=True)

print(text2) # 将多行文本按行分隔,傳回一個清單,保留行尾換行符

python中的diff有什麼作用_python中difflib内置子產品之文本對比

"""

splitlines()按照行分割

傳回一個包含各行作為元素的清單

參數:

keepends=True 保留換行符

keepends=False 不包含換行符

"""

#實作linux裡面類似diff指令的功能

#d = difflib.Differ()

#print(‘‘.join(list(d.compare(text1,text2))))

d = difflib.HtmlDiff()

htmlContent = d.make_file(text1,text2)

#print(htmlContent)

with open(‘diff.html‘,‘w‘) as f:

f.write(htmlContent)

python中的diff有什麼作用_python中difflib内置子產品之文本對比

linux檔案之間的對比

首先将檔案内容讀取出來,然後按照上述方法進行處理即可:

import difflib

filename1 = ‘/tmp/passwd‘

filename2 = ‘/tmp/passwd1‘

with open(filename1) as f1,open(filename2) as f2:

content1 = f1.read().splitlines(keepends=True)

content2 = f2.read().splitlines(keepends=True)

d = difflib.HtmlDiff()

htmlContent = d.make_file(content1,content2)

with open(‘passwdDiff.html‘,‘w‘) as f:

f.write(htmlContent)