python實現字符串差異對比方法


一 點睛

本篇介紹如何通過difflib模塊實現文件內容差異對比。difflib作為 Python的標准庫模塊,無需安裝,作用是對比文本之間的差異,且支持輸出可讀性比較強的HTML文檔,與Linux下的diff命令相似。我們可以使用difflib對比代碼、配置文件的差別,在版本控制方面是非常有用。 Python 2.3或更高版本默認自帶difflib模塊,無需額外安裝。

二 兩個字符串的差異對比

1 點睛

本例通過使用difflib模塊實現兩個字符串的差異對比,然后以版本控制風格進行輸出。

2 代碼

#!/usr/bin/python
import difflib
 
text1 = """
text1:
This module provides classes and functions for comparing sequences.
including HTML and context and unified diffs.
difflib document v7.4
add string
"""
 
text1_lines = text1.splitlines()
 
text2 = """
text2:
This module provides classes and functions 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)))

3 結果

E:\Python\python_auto_maintain\venv\Scripts\python.exe E:/Python/python_auto_maintain/2_1_1.py  
- text1:
?     ^
+ text2:
?     ^
- This module provides classes and functions for comparing sequences.
?                                                ^
+ This module provides classes and functions for Comparing sequences.
?                                                ^
  including HTML and context and unified diffs.
- difflib document v7.4
?                     ^
+ difflib document v7.5
?                     ^
- add string

4 說明

采用Differ()類對兩個字符串進行比較,另外difflib的 SequenceMatcher()類支持任意類型序列的比較,HtmlDiff()類支持將比較結果輸出為HTML格式。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM