Python2 获取docx/doc文件内容

本文介绍了一种使用Python标准库解析DOCX文件的方法,通过下载文件并将其转换为ZIP格式,进一步提取并读取document.xml中的文本内容。

整体思路:

 下载文件并修改后缀为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') 这种方法发现只能解决一部分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()pasting

 

转载于:https://www.cnblogs.com/fanjp666888/p/9877968.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值