通过python读取Docx文件

问题描述 投票:0回答:5

有人知道一个Python库来读取docx文件吗?

我有一个 Word 文档,我正在尝试从中读取数据。

python docx python-docx
5个回答
8
投票

有几个软件包可以让你做到这一点。 检查

  1. python-docx

  2. docx2txt(请注意,它似乎不适用于

    .doc
    )。根据 this,它似乎比 python-docx 获得更多信息。 来自原始文档:

import docx2txt

# extract text
text = docx2txt.process("file.docx")

# extract text and write images in /tmp/img_dir
text = docx2txt.process("file.docx", "/tmp/img_dir") 
  1. texttract(通过docx2txt工作)。

  2. 由于

    .docx
    文件只是扩展名已更改的
    .zip
    文件,因此 this 显示了如何访问其内容。 这是与
    .doc
    文件的显着差异,也是上述部分(或全部)文件不适用于
    .doc
    的原因。 在这种情况下,您可能必须首先转换
    doc
    ->
    docx
    antiword
    是一个选项。


4
投票

python-docx 既可以读也可以写。

doc = docx.Document('myfile.docx')
allText = []
for docpara in doc.paragraphs:
    allText.append(docpara.text)

现在所有段落都将出现在 allText 列表中。

感谢 Al Sweigart 的 Automate the Boring Stuff with Python 的指点。


2
投票

查看这个允许读取 docx 文件的库 https://python-docx.readthedocs.io/en/latest/

您应该使用 PyPi 上提供的 python-docx 库。然后你就可以使用以下

doc = docx.Document('myfile.docx')
allText = []
for docpara in doc.paragraphs:
    allText.append(docpara.text)

1
投票

快速搜索 PyPI 会找到 docx 包。


1
投票
import docx

def main():
    try:
        doc = docx.Document('test.docx')  # Creating word reader object.
        data = ""
        fullText = []
        for para in doc.paragraphs:
            fullText.append(para.text)
            data = '\n'.join(fullText)

        print(data)

    except IOError:
        print('There was an error opening the file!')
        return


if __name__ == '__main__':
    main()

不要忘记使用(pip install python-docx)安装python-docx

© www.soinside.com 2019 - 2024. All rights reserved.