使用 python-docx 和 difflib 对比 Word 文档

使用 python-docx 和 difflib 对比 Word 文档

以下是一个 Python 脚本示例,用于比较两个 Word 文档的文本内容差异:

复制代码
from docx import Document
import difflib

def read_word_file(file_path):
    doc = Document(file_path)
    full_text = []
    for para in doc.paragraphs:
        full_text.append(para.text)
    return '\n'.join(full_text)

def compare_word_files(file1, file2):
    text1 = read_word_file(file1)
    text2 = read_word_file(file2)
    
    d = difflib.Differ()
    diff = list(d.compare(text1.splitlines(), text2.splitlines()))
    
    print('\n'.join(diff))

# 使用示例
compare_word_files('document1.docx', 'document2.docx')

安装依赖库

运行前需要安装 python-docx 和 difflib(后者是 Python 标准库):

复制代码
pip install python-docx

输出结果说明

  • 以 '-' 开头的行表示第一个文档独有的内容
  • 以 '+' 开头的行表示第二个文档独有的内容
  • 以空格开头的行表示两个文档共有的内容

处理复杂格式差异

如果需要比较格式差异(如字体、颜色等),可以使用更专业的库如 python-docx-compare:

复制代码
from docxcompose.composer import Composer
from docx import Document

doc1 = Document("document1.docx")
doc2 = Document("document2.docx")

composer = Composer(doc1)
composer.append(doc2)
composer.save("compared.docx")

可视化差异输出

对于更直观的差异展示,可以生成 HTML 格式的对比结果:

复制代码
diff_html = difflib.HtmlDiff().make_file(
    text1.splitlines(), 
    text2.splitlines(),
    fromdesc='Document 1',
    todesc='Document 2'
)
with open('diff.html', 'w') as f:
    f.write(diff_html)
相关推荐
洵有兮18 分钟前
python第四次作业
开发语言·python
kkoral19 分钟前
单机docker部署的redis sentinel,使用python调用redis,报错
redis·python·docker·sentinel
BoBoZz1934 分钟前
IterativeClosestPoints icp配准矩阵
python·vtk·图形渲染·图形处理
test管家1 小时前
PyTorch动态图编程与自定义网络层实战教程
python
laocooon5238578861 小时前
python 收发信的功能。
开发语言·python
清水白石0081 小时前
《Python 责任链模式实战指南:从设计思想到工程落地》
开发语言·python·责任链模式
沛沛老爹1 小时前
Web开发者快速上手AI Agent:基于LangChain的提示词应用优化实战
人工智能·python·langchain·提示词·rag·web转型
宁大小白1 小时前
pythonstudy Day39
python·机器学习
拾贰_C1 小时前
【VSCode | python | anaconda | cmd | PowerShell】在没有进入conda环境时使用conda命令默认安装位置
vscode·python·conda
大千AI助手2 小时前
基于OpenAPI生成的 SDK 的工业级和消费级概念区别
人工智能·python·机器学习·openai·代码生成·openapi·大千ai助手