小编Sag*_*lin的帖子

在 Python 3 中替换 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 …
Run Code Online (Sandbox Code Playgroud)

python python-3.x python-docx

2
推荐指数
1
解决办法
5601
查看次数

标签 统计

python ×1

python-3.x ×1

python-docx ×1