首页 > 解决方案 > 如何使用“Python docx”在 word 文档的页脚中查找和替换文本

问题描述

在此处输入图像描述我创建了一个 word 文档并使用 python docx 在该文档中添加了一个页脚。但现在我想替换页脚中的文本。

例如:我在页脚中有一个段落,即“第 1 到 10 页”。我想找到单词“to”并将其替换为“of”,所以我的结果将是“Page 1 of 10”。

我的代码:

from docx import Document
document = Document()
document.add_heading('Document Title', 0)
section = document.sections[0]
footer = section.footer
footer.add_paragraph("Page 1 to 10")
document.save('mydoc.docx')

​</p>

标签: pythondocx

解决方案


试试这个解决方案。您将不得不遍历文档中的所有页脚

from docx import Document
document = Document('mydoc.docx')
for section in document.sections:
    footer = section.footer
    footer.paragraphs[1].text  = footer.paragraphs[1].text.replace("to", "of")

document.save('mydoc.docx') 

此代码编辑页脚段落列表的第二个元素的原因是您在代码的页脚中添加了另一个段落。根据文档,默认情况下页脚中已经有一个空段落


推荐阅读