gpt4 book ai didi

python - 用python2.7阅读docx

转载 作者:太空宇宙 更新时间:2023-11-04 10:33:34 25 4
gpt4 key购买 nike

我正在尝试使用以下代码读取包含文件的 docx 文件:

from docx import Document
doc = Document('test.docx')

但是当我尝试打印它时,我得到了这个:

<docx.api.Document object at 0x02952C70>

如何读取文件中的内容?

我读到 docx 最近发生了变化,所以旧的问题/答案不再适用。

最佳答案

在此处查看 Document 对象的结构:

Source code for docx.api

例如,如果你想获取属性“paragraphs”:

doc = Document('test.docx')
paragraphs = doc.paragraphs()

希望对您有所帮助。

编辑:我在 python-docx's gitHub repository 中找到了这个片段并在这里稍微编辑一下:

document = docx.Document(filename)
docText = '\n\n'.join([
paragraph.text.encode('utf-8') for paragraph in document.paragraphs
])
print docText

join() 函数从 paragraphs 属性返回的数组中的段落接收以 UTF-8 编码的字符串列表。所以结果看起来像:

paragraph 1

paragraph 2

paragraph 3

这看起来可行,但它不打印表格、页眉或页脚。

编辑:此链接是有关 python-docx 的所有文档的主要索引:

python-docx 0.7.4 documentation

关于python - 用python2.7阅读docx,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24901344/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com