今天第一个内容是如何处理.docx文件(微端microsoft office广泛使用的文件格式)
微软 Office 产品中 Word 用 .doc 文件格式。这种二进制格式很难读 取,而且能够读取 word 格式的软件很少。为了跟上时代,让自己的软件能够符合主流软 件的标准,微软决定使用 Open Office 的类 XML 格式标准,此后新版 Word 文件才与其他 文字处理软件兼容,这个格式就是 .docx
Python 对 这 种 Google Docs、Open Office 和 Microsoft Office 都 在 使 用 的 .docx 格 式 的 支 持 还 不 够 好,如果想读取 Microsoft Office 文件的正文内容,是没有现有的库能够很好胜任的,我们需要自己动手找方法
第一步是从文件读取 XML
from urllib.request import urlopen
from zipfile import ZipFile
from io import BytesIO
wordFile = urlopen("http://pythonscraping.com/pages/AWordDocument.docx").read()
wordFile = BytesIO(wordFile)
document = ZipFile(wordFile)
xml_content = document.read("word/document.xml")
print(xml_content.decode("utf_8"))
上面这段代码输出下面的内容:
<!--?xml version="1.0" encoding="UTF-8" standalone="yes"?--> <w:document mc:ignorable="w14 w15 wp14" xmlns:m="http://schemas.openx mlformats.org/officeDocument/2006/math" xmlns:mc="http://schemas.open xmlformats.org/markup-compatibility/2006" xmlns:o="urn:schemas-micros oft-com:office:office" xmlns:r="http://schemas.openxmlformats.org/off iceDocument/2006/relationships" xmlns:v="urn:schemas-microsoft-com:vm l" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/m ain" xmlns:w10="urn:schemas-microsoft-com:office:word" xmlns:w14="htt p://schemas.microsoft.com/office/word/2010/wordml" xmlns:w15="http:// schemas.microsoft.com/office/word