在 Python 3 中替换 docx 表中的文本

Sag*_*lin 2 python python-3.x python-docx

我正在使用 python-docx 并尝试替换表保存样式中的文本。 这就是我的桌子的样子

我已经成功地使用以下内容替换了段落:

from docx import Document
def replace_string(doc, to_replace, replacement):
    for p in doc.paragraphs:
        if to_replace in p.text:
            inline = p.runs
            for i in range(len(inline)):
                if to_replace in inline[i].text:
                    text = inline[i].text.replace(to_replace, replacement)
                    inline[i].text = text
    return 1
Run Code Online (Sandbox Code Playgroud)

但它不适用于表格和单元格。我也尝试过这个:

def replace_in_table(doc, to_replace, replacement):
for table in doc.tables:
    for cell in table.cells:
        for p in cell.paragaphs:
            if to_replace in p.text:
                inline = p.runs
                for i in range(len(inline)):
                    if to_replace in inline[i].text:
                        text = inline[i].text.replace(to_replace, replacement)
                        inline[i].text = text
return 1
Run Code Online (Sandbox Code Playgroud)

但我有一个 AttributeError: 'Table' 对象没有属性 'cells'。请帮我解决这个问题

Jac*_*ack 5

查看他们的文档,您可能需要执行以下操作:

for table in doc.tables:
    for row in table.rows:
        for cell in row.cells:
           ...
Run Code Online (Sandbox Code Playgroud)