使用 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)
相关推荐
java1234_小锋4 小时前
TensorFlow2 Python深度学习 - TensorFlow2框架入门 - 使用Keras实现分类问题
python·深度学习·tensorflow·tensorflow2
星期天要睡觉4 小时前
计算机视觉(opencv)——人脸网格关键点检测
python·opencv·计算机视觉
用户8356290780514 小时前
用Python轻松转换Excel表格为HTML格式
后端·python
weixin_307779134 小时前
AWS Redshift 数据仓库完整配置与自动化管理指南
开发语言·数据仓库·python·云计算·aws
Sunsets_Red4 小时前
差分操作正确性证明
java·c语言·c++·python·算法·c#
APIshop5 小时前
代码实例:Python 爬虫抓取与解析 JSON 数据
爬虫·python·json
程序员爱钓鱼5 小时前
Python编程实战 · 基础入门篇 | Python的版本与安装
后端·python
hmbbcsm5 小时前
练习python题目小记
python
ZhengEnCi6 小时前
CMD 与 Python 完全区别指南-小白必看的编程入门解惑宝典
windows·python