【问题标题】:How to change contents of Word document with Python?如何使用 Python 更改 Word 文档的内容?
【发布时间】:2018-02-13 20:03:58
【问题描述】:

我正在尝试使用 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')

【问题讨论】:

  • 你想做什么?为什么您希望能够将Document 转换为list?我建议您阅读Document 的文档以确定它有哪些可用的方法。

标签: python list ms-word python-docx


【解决方案1】:

为了访问 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')

请注意:此代码仅复制文档的文本,没有所有粗体斜体,下划线或彩色部分(仅它们的文本)。它也不会复制不同的字体、表格样式等。 如果您确实想复制每个段落的样式,请参考How do I copy the contents of a word document?

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 我已经试过了。它抛出同样的错误:'Document' object is not iterable...
    • 那是因为您可能仍在尝试将其转换为列表而不是将其添加到列表中
    • 不,我打开了一个空列表并使用 for 循环遍历文档的项目。它不起作用。