【问题标题】:Read Docx files via python通过 python 读取 Docx 文件
【发布时间】:2015-03-27 19:50:48
【问题描述】:

有人知道读取 docx 文件的 python 库吗?

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

【问题讨论】:

  • 我会使用python-docx
  • 不是用来写的吗?不适合阅读
  • 你想从 docx 文件中得到什么信息?只是文字?图片?元数据?
  • 只是文本,但与文档格式相同
  • 另一种方法是使用 libreoffice 命令行将.docx 转换为.odt,然后检查.odt 文件。 AFAIK odt python 工具比 docx 更好。

标签: python docx python-docx


【解决方案1】:

python-docx 可以读写。

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

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

感谢 Al Sweigart 的“How to Automate the Boring Stuff with Python”的指点。

【讨论】:

    【解决方案2】:

    search of PyPI 快速打开docx 包。

    【讨论】:

    【解决方案3】:
    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()
    

    别忘了安装 python-docx 使用 (pip install python-docx)

    【讨论】:

      猜你喜欢
      • 2017-10-26
      • 1970-01-01
      • 2022-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-10
      相关资源
      最近更新 更多