整體思路:
下載文件並修改后綴為zip文件,解壓zip文件,所要獲取的內容在固定的文件夾下:work/temp/word/document.xml
所用包,全部是python自帶,不需要額外下載安裝.
# encoding:utf-8pasting
import os
import re
import requests
import zipfile
import xml.dom.minidom
newfile = 'test.docx'
def create(newfile):
"""下載docx文件,並修改后綴為zip"""
res = requests.get('https://www.cqjbfy.gov.cn/publiccenter/splc/mb/splc_gginfo.asp?newsid=28949')
if not os.path.exists(newfile):
f = open(newfile, 'wb')
for chunk in res.iter_content(100000):
f.write(chunk)
f.close()
os.rename(newfile, 'test.zip') 這種方法發現只能解決一部分doc文件,具體原因不得而知,有明白的歡迎留言# 將doc/docx文件壓縮成zip文件#pf = zipfile.ZipFile('test.zip', 'w', zipfile.ZIP_STORED)
#pf.write(newfile)
def get_txt():
"""解壓zip,並在work/temp/word/document.xml獲取文本內容,進行正則替換標簽等操作"""
f = zipfile.ZipFile('test.zip', 'r')
for file in f.namelist():
f.extract(file, "temp/")
f = xml.dom.minidom.parse('./temp/word/document.xml')
txt = re.sub(r'</w:t></w:r></w:p>', '\n', f.toxml())
print re.sub(r'<.*?>', '', txt)
if __name__ == '__main__':
create(newfile)
get_txt()