You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用python-docx访问形状与文本框中的文本内容?

解决python-docx无法替换形状内文本的问题

你的代码仅处理了文档顶层的普通段落,而Word中形状(如文本框、自选图形)内的文本并不在doc.paragraphs集合中,而是存储在形状的text_frame对象里,因此需要单独遍历处理这部分内容。

完整解决方案代码

from docx import Document

def replace_text_in_paragraphs(paragraphs, replace_dict):
    """批量替换指定段落集合中的文本"""
    for p in paragraphs:
        for old_word, new_word in replace_dict.items():
            if old_word in p.text:
                p.text = p.text.replace(old_word, new_word)

# 加载文档
doc = Document('template.docx')
replace_map = {'Captain': 'Gerard B. Geronimo'}

# 1. 处理文档顶层的普通段落
replace_text_in_paragraphs(doc.paragraphs, replace_map)

# 2. 处理文档中的所有形状(文本框、自选图形等)
for shape in doc.shapes:
    # 仅处理包含文本框的形状
    if shape.has_text_frame:
        text_frame = shape.text_frame
        # 替换文本框内的段落文本
        replace_text_in_paragraphs(text_frame.paragraphs, replace_map)
        # 可选:处理文本框内表格的文本
        for table in text_frame.tables:
            for row in table.rows:
                for cell in row.cells:
                    replace_text_in_paragraphs(cell.paragraphs, replace_map)

# 可选:处理页眉页脚中的形状文本
for section in doc.sections:
    # 处理页眉形状
    for shape in section.header.shapes:
        if shape.has_text_frame:
            replace_text_in_paragraphs(shape.text_frame.paragraphs, replace_map)
    # 处理页脚形状
    for shape in section.footer.shapes:
        if shape.has_text_frame:
            replace_text_in_paragraphs(shape.text_frame.paragraphs, replace_map)

# 保存修改后的文档
doc.save('note_demo.docx')

关键说明

  • shape.has_text_frame:用于过滤掉无文本内容的纯图形形状,避免无效处理
  • text_frame.paragraphs:形状内的文本以段落形式存储,和普通段落的处理逻辑一致
  • 额外处理了形状内的表格:如果你的文档中存在带文本的表格嵌套在形状里,这部分代码可以覆盖到
  • 页眉页脚的形状处理:如果需要替换页眉页脚中的形状文本,取消对应代码注释即可

内容的提问来源于stack exchange,提问作者John Wilmer Dela Cerna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 20:32:12