如何用Python更改Word文档的内容?

How to change contents of Word document with Python?

我正在尝试使用 word 文档来更改其内容。当我尝试以下代码时,它不起作用,因为 'Document' object is not iterable.

from docx import Document

doc = Document('SomeDocument.docx')
doc_list = list(doc)

some_list = []
for item in doc_list:
    if item == 'something':
        some_list.append(item)

some_list.save('DocumentOutput.docx')

不要将文档转换为列表,而是尝试使用循环将文档中的所有单词附加到列表中 删除:list(doc) 并将其更改为 []

然后制作你的 for 循环并附加每个单词

为了访问 Word 文档中的文本,您需要使用 docx-python 中的 text 函数。如果您想操纵文档的文本,您可以通过将文本存储在列表中来使用列表,然后用它做任何您想做的事。

doc = Document('SomeDocument.docx')

paragraphs = []
for paragraph in doc.paragraphs:
    p = paragraph.text
    paragraphs.append(p)


output = Document()
for item in questions_answers:
    line = test.add_paragraph(item)

output.save('OutputDocument.docx')

Please Note: This code only copies the text of the document without all the bold, italic, underlined nor colored parts as they are (only their text). Neither will it copy the different fonts, table styles etc. If you do want to copy the styles of each paragraph, please refer to How do I copy the contents of a word document? .