【问题标题】:Reading a .doc extension file ,ElementTree读取 .doc 扩展文件,ElementTree
【发布时间】:2014-09-15 05:26:11
【问题描述】:

我已经使用 zipfile 使用 ElementTree 包成功读取了 .docx 文件。但我意识到没有档案 'word/document.xml'for .doc files 。我查看了文档,但没有找到任何文档。怎么读? 对于 docx,我使用了:

import zipfile as zf
import xml.etree.ElementTree as ET
z = zf.ZipFile("test.docx")
doc_xml = z.open('word/document.xml')
tree = ET.parse(doc_xml)

对 .doc 使用上述内容:

KeyError: "There is no item named 'word/document.xml' in the archive"

我在 ElementTree 文档中看到了一些可供阅读的内容,但这仅适用于 xml 文件。

doc_xml = open('yesblue.doc','r')  

这个应该怎么做?可能类似于在 python 本身中将.doc 转换为.docx

编辑:.doc 格式以二进制形式存储数据,不能使用 XML。

【问题讨论】:

    标签: xml python-2.7 docx elementtree doc


    【解决方案1】:

    经过一番认真的搜索,我意识到最好使用 comtypes 包将其从.doc 转换为.docx 格式。这有其自身的一系列缺点,例如Windows exclusivity 和需要安装 Microsoft Office。

    import sys
    import os
    import comtypes.client
    in_file = os.path.abspath('')
    out_file = os.path.abspath('yesblue') #name of output file added to the current working directory 
    word = comtypes.client.CreateObject('Word.Application')
    doc = word.Documents.Open('yesblue.doc') #name of input file
    doc.SaveAs(out_file, FileFormat=16)  # output file format to Office word Xml default (code=16)
    doc.Close()
    word.Quit()    
    

    代码列表包含here

    输出的docx 文件可用于ElementTree 中的进一步处理。

    【讨论】:

      猜你喜欢
      • 2022-01-24
      • 2021-03-11
      • 1970-01-01
      • 1970-01-01
      • 2018-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多