使用 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)
相关推荐
我材不敲代码1 小时前
Python实现打包贪吃蛇游戏
开发语言·python·游戏
0思必得03 小时前
[Web自动化] Selenium处理动态网页
前端·爬虫·python·selenium·自动化
韩立学长3 小时前
【开题答辩实录分享】以《基于Python的大学超市仓储信息管理系统的设计与实现》为例进行选题答辩实录分享
开发语言·python
qq_192779873 小时前
高级爬虫技巧:处理JavaScript渲染(Selenium)
jvm·数据库·python
u0109272714 小时前
使用Plotly创建交互式图表
jvm·数据库·python
爱学习的阿磊4 小时前
Python GUI开发:Tkinter入门教程
jvm·数据库·python
Imm7774 小时前
中国知名的车膜品牌推荐几家
人工智能·python
tudficdew5 小时前
实战:用Python分析某电商销售数据
jvm·数据库·python
sjjhd6525 小时前
Python日志记录(Logging)最佳实践
jvm·数据库·python
2301_821369615 小时前
用Python生成艺术:分形与算法绘图
jvm·数据库·python