萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python difflib 實現文本差異比對:逐行/逐字/HTML 報表完整教學

標準庫 difflib 核心類別

類別用途輸出格式
Differ逐行比對,產生人類可讀差異標記列表,每行前綴 + - ?
SequenceMatcher任意序列比對 (字串、列表),支援相似度計算匹配區塊、opcodes、ratio()
HtmlDiff生成並排/內聯 HTML 差異報表完整 HTML 字串
unified_diff/context_diff產生標準 unified/context diff 格式行迭代器 (類 git diff)

基礎範例:逐行比對 (Differ)


import difflib

text1 = """第一行
第二行
第三行
第四行"""

text2 = """第一行
修改後的第二行
第三行
新增的第五行"""

# 1. 分割為行列表 (保留換行符 keepends=True)
lines1 = text1.splitlines(keepends=True)
lines2 = text2.splitlines(keepends=True)

# 2. 執行比對
differ = difflib.Differ()
diff = list(differ.compare(lines1, lines2))

# 3. 輸出結果
print("完整差異標記:")
for line in diff:
    print(line, end='')

# 4. 篩選特定變更
print("\n--- 仅显示变更 ---")
for line in diff:
    if line.startswith(('+ ', '- ', '? ')):
        print(line, end='')

輸出標記含義

  • (兩空格) - 無變更
  • - - 僅在舊文本 (刪除)
  • + - 僅在新文本 (新增)
  • ? - 輔助標記行,指示字元級變化位置 (^ + -)

進階:HTML 並排差異報表


html_diff = difflib.HtmlDiff(tabsize=4, wrapcolumn=80)
html_output = html_diff.make_file(lines1, lines2, 
                                   fromdesc="原始版本", 
                                   todesc="修改版本",
                                   context=True,      # True=上下文模式, False=完整檔案
                                   numlines=3)        # 上下文模式顯示的上下文行數

with open("diff_report.html", "w", encoding="utf-8") as f:
    f.write(html_output)
print("HTML 差異報表已生成: diff_report.html")

SequenceMatcher:相似度與區塊匹配


matcher = difflib.SequenceMatcher(None, text1, text2)

# 1. 相似度比率 (0.0~1.0)
print(f"相似度: {matcher.ratio():.2%}")

# 2. 獲取匹配區塊 (start_a, start_b, size)
for block in matcher.get_matching_blocks():
    if block.size > 0:
        print(f"匹配: text1[{block.a}:{block.a+block.size}] == text2[{block.b}:{block.b+block.size}]")
        print(f"  內容: {repr(text1[block.a:block.a+block.size])}")

# 3. 獲取操作碼 (opcode) 可構建自定義差異視覺化
for tag, i1, i2, j1, j2 in matcher.get_opcodes():
    print(f"{tag:7} text1[{i1}:{i2}] --> text2[{j1}:{j2}]")
    # tag: 'equal', 'replace', 'delete', 'insert'

unified_diff:生成標準 Patch 格式


# 產生類似 git diff -u 的輸出
patch = difflib.unified_diff(lines1, lines2, 
                             fromfile="old.txt", tofile="new.txt",
                             lineterm="") # lineterm="" 避免雙重換行
sys.stdout.writelines(line + "\n" for line in patch)

效能與大檔案策略

  • SequenceMatcher 時間複雜度 O(N*D) (N=長度, D=編輯距離),極長字串 (>10MB) 會明顯變慢。
  • 大檔案建議:先逐行比對 (Differ) 定位變更區塊,再對變更區塊用 SequenceMatcher 細粒度分析。
  • 或使用外部工具 diff-match-patch (Google) 支援增量演算法。
copyright © 萬盛學電腦網 all rights reserved