如何使用 "Python docx" 查找和替换 word 文档页脚中的文本
How can I find and replace a text in footer of word document using "Python docx"
enter image description here我创建了一个 word 文档并使用 python docx 在该文档中添加了页脚。但是现在我想替换页脚中的文本。
例如:我在页脚中有一个段落,即 "Page 1 to 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')
试试这个解决方案。
您将不得不遍历 document
中的所有页脚
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')
此代码编辑页脚段落列表的第二个元素的原因是您在代码中向页脚添加了另一个段落。默认情况下,根据 documentation
,页脚中已经有一个空段落
我知道这是一个老问题,但接受的答案会更改页脚的页码,如果您想解决该问题,则需要编辑 XML。相反,我发现如果您使用 Runs 编辑文本,它将保留 header/footer 的原始格式。 https://python-docx.readthedocs.io/en/latest/api/text.html#docx.text.run.Run
from docx import Document
document = Document('mydoc.docx')
for section in document.sections:
footer = section.footer
footer.paragraphs[1].runs[0].text = footer.paragraphs[1].runs[0].text.replace("to", "of")
document.save('mydoc.docx')
enter image description here我创建了一个 word 文档并使用 python docx 在该文档中添加了页脚。但是现在我想替换页脚中的文本。
例如:我在页脚中有一个段落,即 "Page 1 to 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')
试试这个解决方案。 您将不得不遍历 document
中的所有页脚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')
此代码编辑页脚段落列表的第二个元素的原因是您在代码中向页脚添加了另一个段落。默认情况下,根据 documentation
,页脚中已经有一个空段落我知道这是一个老问题,但接受的答案会更改页脚的页码,如果您想解决该问题,则需要编辑 XML。相反,我发现如果您使用 Runs 编辑文本,它将保留 header/footer 的原始格式。 https://python-docx.readthedocs.io/en/latest/api/text.html#docx.text.run.Run
from docx import Document
document = Document('mydoc.docx')
for section in document.sections:
footer = section.footer
footer.paragraphs[1].runs[0].text = footer.paragraphs[1].runs[0].text.replace("to", "of")
document.save('mydoc.docx')