【发布时间】:2022-05-02 05:45:00
【问题描述】:
我正在尝试编写一个应用程序从 word docx 文件中的表中获取信息,以便通过将其转换为 pandas DataFrame 对其进行一些分析。第一步是正确阅读 docx 文件,为此,我遵循 Virantha Ekanayake 的 Reading and writing Microsoft Word docx files with Python 指南。
我处于他们说使用zipfile 库的Zipfile 方法将docx 文件解压缩为xml 文件的第一步。我将指南中的函数定义改编成我的代码(代码包含在下面),但是当我运行我的代码时,我收到一条错误消息,指出 docx 文件“不是 zip 文件”。
指南中的这个人说,“从本质上讲,docx 文件只是一个 zip 文件(尝试在其上运行 unzip!)...”我尝试将 docx 文件重命名为 zip 文件,并且它成功解压缩使用 WinZip。但是,在我的程序中,我希望能够解压缩 docx 文件,而不必手动将其重命名为 .zip 文件。我是否能够以某种方式解压缩 docx 文件而不重命名它? 或者,如果我必须重命名它才能使用Zipfile 方法,我该如何在我的python 代码中执行此操作?
import zipfile
from lxml import etree
import pandas as pd
FILE_PATH = 'C:/Users/user/Documents/Python Project'
class Application():
def __init__(self):
#debug print('Initialized!')
xml_content = self.get_word_xml(f'{FILE_PATH}/DocxFile.docx')
xml_tree = self.get_xml_tree(xml_content)
def get_word_xml(self, docx_filename):
with open(docx_filename) as f:
zip = zipfile.ZipFile(f)
xml_content = zip.read('word/document.xml')
return xml_content
def get_xml_tree(self, xml_string):
return (etree.fromstring(xml_string))
a = Application()
a.mainloop()
错误:
Traceback (most recent call last):
File "C:\Users\user\Documents\New_Tool.py", line 39, in <module>
a = Application()
File "C:\Users\user\Documents\New_Tool.py", line 27, in __init__
xml_content = self.get_word_xml(f'{FILE_PATH}/DocxFile.docx')
File "C:\Users\user\Documents\New_Tool.py", line 32, in get_word_xml
zip = zipfile.ZipFile(f)
File "C:\Progra~1\Anaconda3\lib\zipfile.py", line 1222, in __init__
self._RealGetContents()
File "C:\Progra~1\Anaconda3\lib\zipfile.py", line 1289, in _RealGetContents
raise BadZipFile("File is not a zip file")
zipfile.BadZipFile: File is not a zip file
【问题讨论】:
-
zipfile.ZipFile不在乎文件的名称或扩展名是什么,所以问题出在其他问题上。
标签: python python-3.7 docx python-zipfile