Python如何批量实现查找替换Word文档的文本内容
查找替换是 Word 文档处理中最高频的操作。合同里改公司名称、报告里更新日期、模板里把占位符换成实际内容——手动做几十份文档既慢又容易出错。用程序做,不仅能批量处理,还能把一段文本替换成图片、表格等结构化内容,这是手动查找替换做不到的。
本文使用 Free Spire.Doc for Python 演示 Word 查找替换的几种形态:精确文本替换、正则匹配替换、查找高亮、替换为图片、替换为表格,以及对多份文档的批量处理。
pip install spire.doc.free
以下示例使用一份服务协议文档(sample.docx)作为输入。文档包含公司名称 TechCorp Solutions、客户名称 Global Systems Inc、日期 January 15, 2026、三个标签 #TAG001 #TAG002 #TAG003,以及 [LOGO] 和 [PRICING_TABLE] 两个占位符。

文本替换:精确匹配与选项控制
Document.Replace 方法接受四个参数:查找文本、替换文本、是否区分大小写、是否全词匹配。全词匹配为 True 时,查找 "Provider" 不会匹配 "Providers" 中的子串。
from spire.doc import *
from spire.doc.common import *
document = Document()
document.LoadFromFile("sample.docx")
# 替换公司名称
document.Replace("TechCorp Solutions", "Innovatech Partners", False, True)
# 替换客户名称
document.Replace("Global Systems Inc", "Apex Dynamics Ltd", False, True)
# 替换日期
document.Replace("January 15, 2026", "March 20, 2026", False, True)
document.SaveToFile("after_text_replace.docx", FileFormat.Docx)
document.Close()运行后文档中三处文本被替换:
Text replacement complete: after_text_replace.docx
Replaced: TechCorp Solutions -> Innovatech Partners
Replaced: Global Systems Inc -> Apex Dynamics Ltd
Replaced: January 15, 2026 -> March 20, 2026
Replace 方法会遍历文档正文、页眉页脚、表格单元格中的所有段落,不需要手动逐段搜索。第三个参数 False 表示区分大小写,第四个参数 True 表示只匹配完整单词。如果要把 "cat" 替换成 "dog" 但不想影响 "category",全词匹配就能避免误替换。

正则表达式匹配替换
当要替换的文本具有固定模式而非固定字符串时,用正则表达式匹配。文档中的 #TAG001、#TAG002、#TAG003 是变更管理标签,需要统一替换为 "RESOLVED"。
Spire.Doc 提供 Regex 类和 FindAllPattern 方法用于正则匹配。FindAllPattern 返回所有匹配的文本选择对象,逐个修改其 Text 属性即可完成替换:
from spire.doc import *
from spire.doc.common import *
document = Document()
document.LoadFromFile("sample.docx")
# 创建正则表达式,匹配 #TAG 后跟字母数字
regex = Regex("#TAG\\w+", RegexOptions.none)
# 查找所有匹配项
textSections = document.FindAllPattern(regex)
# 逐项替换文本
for ts in textSections:
textRange = ts.GetAsOneRange()
textRange.Text = "RESOLVED"
document.SaveToFile("after_regex_replace.docx", FileFormat.Docx)
document.Close()运行结果:
Found 3 regex matches
Regex replacement complete: after_regex_replace.docx
Pattern: #TAG\w+ -> RESOLVED
Matched: #TAG001, #TAG002, #TAG003
Regex 类使用 .NET 正则语法,\\w+ 匹配一个或多个字母数字字符。RegexOptions.none 表示不使用特殊选项(如忽略大小写、多行模式等)。FindAllPattern 返回的每个 TextSelection 对象通过 GetAsOneRange() 获取 TextRange,直接设置 Text 属性就能替换文本内容,原有格式保持不变。
正则替换适用于批量处理有规律的文本:统一日期格式(\d{4}/\d{2}/\d{2} → \d{4}-\d{2}-\d{2})、脱敏邮箱地址、更新编号前缀等。
查找文本并高亮标记
有时不需要替换文本,只需要定位并标记。FindAllString 方法返回文档中所有匹配位置,通过 GetAsOneRange() 获取文本范围后,可以设置高亮颜色:
from spire.doc import *
from spire.doc.common import *
document = Document()
document.LoadFromFile("sample.docx")
# 查找 "Agreement" 并高亮为黄色
selections = document.FindAllString("Agreement", False, True)
for selection in selections:
selection.GetAsOneRange().CharacterFormat.HighlightColor = Color.get_Yellow()
# 查找 "Provider" 并高亮为绿色
selections = document.FindAllString("Provider", False, True)
for selection in selections:
selection.GetAsOneRange().CharacterFormat.HighlightColor = Color.get_Green()
# 查找 "Client" 并高亮为橙色
selections = document.FindAllString("Client", False, True)
for selection in selections:
selection.GetAsOneRange().CharacterFormat.HighlightColor = Color.FromArgb(255, 255, 128, 0)
document.SaveToFile("after_highlight.docx", FileFormat.Docx)
document.Close()运行后输出各关键词的出现次数:
Found 'Agreement': 5 occurrences, highlighted yellow
Found 'Provider': 3 occurrences, highlighted green
Found 'Client': 3 occurrences, highlighted orange
Highlight complete: after_highlight.docx
"Agreement" 出现 5 次——标题中 1 次、引言段落中 2 次(带引号和不带引号各 1 次)、终止条款中 1 次、保密条款中 1 次。FindAllString 搜索范围覆盖整个文档正文,不限于单个段落或章节。
Color.FromArgb 的四个参数是透明度(0–255)、红、绿、蓝分量。Color.get_Yellow() 和 Color.get_Green() 是预设颜色的快捷方法,Color.FromArgb(255, 255, 128, 0) 自定义了橙色用于区分不同关键词。

将文本替换为图片
占位符文本可以替换为图片。文档中的 [LOGO] 占位符需要替换为公司 Logo。FindAllString 找到占位符位置后,创建 DocPicture 对象加载图片,在文本范围所在段落中插入图片并移除原文本:
from spire.doc import *
from spire.doc.common import *
document = Document()
document.LoadFromFile("sample.docx")
# 查找所有 [LOGO] 占位符
selections = document.FindAllString("[LOGO]", False, False)
for selection in selections:
# 创建图片对象并加载文件
pic = DocPicture(document)
pic.LoadImage("logo.png")
# 获取文本范围在段落中的位置
textRange = selection.GetAsOneRange()
index = textRange.OwnerParagraph.ChildObjects.IndexOf(textRange)
# 先插入图片,再移除文本
textRange.OwnerParagraph.ChildObjects.Insert(index, pic)
textRange.OwnerParagraph.ChildObjects.Remove(textRange)
document.SaveToFile("after_image_replace.docx", FileFormat.Docx)
document.Close()运行结果:
Found '[LOGO]' placeholder: 1 occurrence(s)
Image replacement complete: after_image_replace.docx
Replaced [LOGO] with logo.png
插入顺序不能反:必须先 Insert 再 Remove。如果先移除文本范围,ChildObjects 的索引会前移,图片会插入到错误的位置。DocPicture 的构造参数是所属文档对象,LoadImage 接受图片文件路径,支持 PNG、JPEG、BMP 等常见格式。

将文本替换为表格
把占位符替换为表格的逻辑与图片不同。表格是块级元素,不能插入到段落的子对象中——需要替换的是包含占位符的整个段落。FindString(单数)返回第一个匹配位置,通过 OwnerParagraph 和 OwnerTextBody 定位段落,在段落所在位置插入表格并移除原段落:
from spire.doc import *
from spire.doc.common import *
document = Document()
document.LoadFromFile("sample.docx")
section = document.Sections[0]
# 查找 [PRICING_TABLE] 占位符
selection = document.FindString("[PRICING_TABLE]", False, False)
# 获取占位符所在的段落和文档体
range = selection.GetAsOneRange()
paragraph = range.OwnerParagraph
body = paragraph.OwnerTextBody
index = body.ChildObjects.IndexOf(paragraph)
# 创建 4 行 3 列的定价表
table = section.AddTable(True)
table.ResetCells(4, 3)
# 填充表头
header = ["Service Item", "Unit Price (USD)", "Quantity"]
for col, text in enumerate(header):
cell = table.Rows[0].Cells[col]
cellParagraph = cell.AddParagraph()
cellParagraph.AppendText(text)
# 填充数据行
data = [
["Cloud Infrastructure", "2,500/month", "1"],
["Data Migration", "8,000", "1"],
["Technical Support", "1,200/month", "1"],
]
for rowIdx, rowData in enumerate(data):
for col, text in enumerate(rowData):
cell = table.Rows[rowIdx + 1].Cells[col]
cellParagraph = cell.AddParagraph()
cellParagraph.AppendText(text)
# 用表格替换占位符段落
body.ChildObjects.Remove(paragraph)
body.ChildObjects.Insert(index, table)
document.SaveToFile("after_table_replace.docx", FileFormat.Docx)
document.Close()运行结果:
Found '[PRICING_TABLE]' placeholder
Table replacement complete: after_table_replace.docx
Replaced [PRICING_TABLE] with 4x3 pricing table
section.AddTable(True) 的参数 True 表示应用默认表格边框样式。ResetCells(4, 3) 初始化 4 行 3 列的空表格,之后通过 Rows[i].Cells[j] 访问每个单元格并添加段落文本。body.ChildObjects 是文档体的子对象集合,Remove 移除段落、Insert 在原位置插入表格,保持文档结构连贯。

批量处理多份文档
实际场景中经常需要对目录下的多份文档执行相同的替换操作。结合 Python 的文件遍历能力,将替换规则定义为列表,循环处理每个文件:
import os
import shutil
from spire.doc import *
from spire.doc.common import *
# 定义替换规则:(查找文本, 替换文本, 区分大小写, 全词匹配)
replacements = [
("TechCorp Solutions", "Innovatech Partners", False, True),
("Global Systems Inc", "Apex Dynamics Ltd", False, True),
("January 15, 2026", "March 20, 2026", False, True),
]
# 准备批量输入目录(3 份文档副本)
batch_dir = "batch_input"
os.makedirs(batch_dir, exist_ok=True)
for i in range(1, 4):
shutil.copy("sample.docx", os.path.join(batch_dir, f"agreement_{i}.docx"))
# 处理目录中的所有 .docx 文件
output_dir = "batch_output"
os.makedirs(output_dir, exist_ok=True)
for filename in sorted(os.listdir(batch_dir)):
if not filename.endswith(".docx"):
continue
doc = Document()
doc.LoadFromFile(os.path.join(batch_dir, filename))
for findText, replaceText, isCase, isWhole in replacements:
doc.Replace(findText, replaceText, isCase, isWhole)
doc.SaveToFile(os.path.join(output_dir, filename), FileFormat.Docx)
doc.Close()
print(f" Processed: {filename}")运行结果:
Created 3 documents in batch_input/
Processed: agreement_1.docx
Processed: agreement_2.docx
Processed: agreement_3.docx
Batch processing complete: 3 documents processed
Output directory: batch_output/
替换规则定义在循环外部,对所有文档统一应用。如果不同文档需要不同的替换规则,可以按文件名匹配规则字典。Document 对象在每次循环中创建和关闭,避免内存累积。
适用场景与嵌入方式
以上六种操作覆盖了 Word 查找替换的主要需求。文本替换适合改名称、改日期等定点修改;正则替换适合处理有规律的批量文本;查找高亮适合文档审核和关键词定位;替换为图片和表格适合模板填充——在模板中放置占位符,运行时替换为实际内容。批量处理把单文档操作扩展到目录级别,适配合同批量生成、报告批量更新等场景。
在业务流程中,查找替换通常作为文档处理管线的一个环节。上游系统(数据库、Excel、API)提供替换数据,Python 脚本读取数据、加载模板、执行替换、输出文档,下游接入邮件发送、归档存储或审批流程。替换规则可以用 JSON 或 YAML 配置文件管理,避免硬编码在脚本中。
以上就是Python如何批量实现查找替换Word文档的文本内容的详细内容,更多关于Python查找替换Word内容的资料请关注脚本之家其它相关文章!
相关文章
pyspark操作hive分区表及.gz.parquet和part-00000文件压缩问题
这篇文章主要介绍了pyspark操作hive分区表及.gz.parquet和part-00000文件压缩问题,针对问题整理了spark操作hive表的几种方式,需要的朋友可以参考下2021-08-08
PyCharm配置外部工具PyQtDesigner、PyUIC、Pyrcc实践
这篇文章介绍了如何在PyCharm中配置和使用PyQt Designer、PyUIC和Pyrcc工具,包括安装必要的库、添加外部工具和配置路径等步骤2026-03-03


最新评论