如何使用Interop在Microsoft Word(.docx)文件中查找替换文本?
替换Word文档(.docx)中指定文本的方案

实现步骤
安装依赖库
使用Python的python-docx库操作docx文件,先执行安装命令:pip install python-docx编写替换代码
以下代码可替换文档中段落、表格、页眉页脚里的指定文本:from docx import Document import re def replace_docx_text(input_file, output_file, target_text, replace_text): # 加载原始文档 doc = Document(input_file) # 替换段落中的文本 for para in doc.paragraphs: if target_text in para.text: # 普通大小写敏感替换 para.text = para.text.replace(target_text, replace_text) # 若需不区分大小写替换,用下方代码替代上一行 # para.text = re.sub(target_text, replace_text, para.text, flags=re.IGNORECASE) # 替换表格中的文本 for table in doc.tables: for row in table.rows: for cell in row.cells: for para in cell.paragraphs: if target_text in para.text: para.text = para.text.replace(target_text, replace_text) # 替换页眉页脚中的文本 for section in doc.sections: # 处理页眉 for para in section.header.paragraphs: if target_text in para.text: para.text = para.text.replace(target_text, replace_text) # 处理页脚 for para in section.footer.paragraphs: if target_text in para.text: para.text = para.text.replace(target_text, replace_text) # 保存修改后的文档 doc.save(output_file) # 调用示例:将"原始文档.docx"中的"A"替换为"B",保存为"修改后文档.docx" replace_docx_text("原始文档.docx", "修改后文档.docx", "A", "B")
注意事项
- 代码会生成新文档,不会覆盖原文件,避免数据丢失
- 若文本存在于文本框、形状或嵌入对象中,
python-docx支持有限,Windows环境可考虑用pywin32调用本地Word客户端实现 - 正则替换可实现模糊匹配、批量替换相似文本等复杂需求
内容的提问来源于stack exchange,提问作者Alex I1
相关产品推荐
相关产品推荐

