【问题标题】:Issues with updating a word document using docx使用 docx 更新 word 文档的问题
【发布时间】:2021-01-02 17:57:33
【问题描述】:

我真的很陌生,所以请温柔一点。我一直在寻找几个小时来解决这个问题。本质上,我正在尝试打开一个 word 文档,在我放入的一个非常简单的表格中找到“X”字符,然后将其更新为用户输入的任何内容。我在这里做的最后一件事是让它成为一个函数并调用它,看看我是否可以解决一些我认为我遇到的问题,它正确地捕获了用户的输入。它看起来像下面的 IDLE。我试图用 Cabbage 替换 X,所以这就是下面显示的内容。问题是,在我运行这个之后,我打开了 word 文档(现在是第 N 次),它只是没有更新说“Cabbage”。我在这里可能做错了什么?我没有收到任何错误消息。我在没有函数和函数调用的情况下试过这个,但它没有:

>>> import os
>>> from docx import Document
>>> import docx
>>> doc=Document('Temp.docx')
>>> def tupdate(rep):
    for table in doc.tables:
        for col in table.columns:
            for cell in col.cells:
                for p in cell.paragraphs:
                     if 'X' in p.text:
                        p.text.replace("X", rep)

                        
>>> rep = input()
Cabbage
>>> tupdate(rep)
>>> doc.save('Temp.docx') 

任何帮助将不胜感激。我在 windows 上使用最新版本的 python。

谢谢。

【问题讨论】:

  • p.text.replace("X", rep) 不进行就地替换。
  • 谢谢。这是我的担忧之一。你能指出什么可以实现这一目标吗?
  • 看看能不能设置p.text = p.text.replace("X", rep)

标签: python docx


【解决方案1】:

p.text.replace("X", rep) 不进行就地替换。

我已经测试了下面的代码,我能够用 Zs 替换 Xs。

import os

from docx import Document

doc = Document('Temp.docx')
rep = 'Z'  # input()

for table in doc.tables:
    for col in table.columns:
        for cell in col.cells:
            for p in cell.paragraphs:
                if 'X' in p.text:
                    p.text = p.text.replace("X", rep)

doc.save('Temp.docx')

【讨论】:

  • 感谢您对此的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多