Python2 获取docx/doc文件内容

整体思路:

 下载文件并修改后缀为zip文件,解压zip文件,所要获取的内容在固定的文件夹下:work/temp/word/document.xml

所用包,全部是python自带,不需要额外下载安装. 

# encoding:utf-8
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')


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()
pasting

猜你喜欢

转载自www.cnblogs.com/fanjp666888/p/9877968.html