python - 如何使用“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>
解决方案
试试这个解决方案。您将不得不遍历文档中的所有页脚
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')
此代码编辑页脚段落列表的第二个元素的原因是您在代码的页脚中添加了另一个段落。根据文档,默认情况下页脚中已经有一个空段落
推荐阅读
- c - 卡住空指针和空字符串检查
- c - ac 函数在有效行为后返回零是标准的吗?
- ocaml - 四叉树迷宫中的 OCaml 寻路
- javascript - 尝试检索页面上元素的值时未定义
- grid - 选择 Dynamics CRM 网格中的所有行
- webpack - 如何使用 webpack 仅编译 LESS 文件
- javascript - 使用量角器配置为 Allure 中的多个浏览器截屏
- python - 扩展 pandas DataFrame 列中的整数范围
- performance - EF 6.2代码优先,简单查询耗时很长
- php - 在 preg_match_all 之后,如果它在另一行中,如何获取该值