我正在嘗試編寫一個應(yīng)用程序從 word docx 文件中的表中獲取信息,以便通過將其轉(zhuǎn)換為 pandas 對其進(jìn)行一些分析DataFrame。第一步是正確讀取 docx 文件,為此,我遵循 Virantha Ekanayake 的Reading and writing Microsoft Word docx files with Python指南。我在第一步,他們說要使用庫Zipfile的方法zipfile將 docx 文件解壓縮到 xml 文件中。我將指南中的函數(shù)定義改編為我的代碼(下面包含的代碼),但是當(dāng)我運(yùn)行我的代碼時,我收到一條錯誤消息,指出 docx 文件“不是 zip 文件”。指南中的這個人說,“本質(zhì)上,docx 文件只是一個 zip 文件(嘗試在其上運(yùn)行解壓縮?。蔽覈L試將 docx 文件重命名為 zip 文件,并使用 WinZip 成功解壓縮。但是,在我的程序中,我希望能夠解壓縮 docx 文件而不必手動.zip將其重命名為文件。我能以某種方式解壓縮 docx 文件而不重命名它嗎?或者,如果我必須重命名它才能使用該方法,我該如何在我的 python 代碼中執(zhí)行此操作?Zipfileimport zipfilefrom lxml import etreeimport pandas as pdFILE_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_xmlzip = 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 _RealGetContentsraise BadZipFile("File is not a zip file")zipfile.BadZipFile: File is not a zip file
添加回答
舉報(bào)
0/150
提交
取消