#!/usr/bin/env python
# coding: utf-8
import zipfile #压缩包
import os #文件库
import shutil
import pytesseract
import PIL
from PIL import Image
from docx import Document ##需要安装第三方库,python-docx
from docx.shared import Pt #用于设置字体样式
from docx.oxml.ns import qn # 中文格式
class get_result:
	def __init__(self,dir_str,file_list,b)
		self.dir_str=dir_str
		self.file_list=file_list
		self.b=b		
	def get_image(self):
		file_list=self.file_list
		dir_str=self.dir_str
		b=self.b
		# 提取word文档中的图片
		for s in file_list:
		    #print (s)
		    file_path=dir_str.format(s)
		    try:
		        doc=zipfile.ZipFile(file_path)#压缩文件
		        r_path=b+"\\image\\{0}".format(s)
		        if os.path.exists(r_path)!=0:
		            shutil.rmtree(r_path) #os.removedirs,如果目录下不为空则不能删除,shutil.rmtree可强制删除文件夹
		        os.mkdir(r_path)
		        for info in doc.infolist():
		            if info.filename.endswith((".jpeg",'.jpg','.png','.gif')):#判断文件类型
		                doc.extract(info.filename,r_path)        
		    except Exception as e:
		        print (e)
		    finally:
		        pass
		print ("图片提取完成")
		
	def insert_word(self):
		file_list=self.file_list	
		b=self.b
		####提取图片中的文字,并写入word/txt文档
		for s in file_list:
		    #print (s)
		    try:
		        r_path=b+"\\image\\{0}\\word\\media".format(s)#图片路径
				#txt_path=b+"\\{0}.txt".format(s)#写入文件路径
		        docx_path=b+"\\{0}.docx".format(s)
		        t=""
		        if os.path.exists(r_path)!=0:
		            for filename in os.listdir(r_path):
		                t=t+"\n"+str(pytesseract.image_to_string(Image.open(r_path+"\\"+filename),lang="chi_sim"))
		            '''
		            写入txt文件
		            fd=open(txt_path,'w')#w 将覆盖原文件内容,a,向原文件追加内容
		            fd.write(t)
		            fd.close()  
		            '''           
		            '''写入word文档'''
		            doc=Document()
		            doc.styles["Normal"].font.name = u"微软雅黑"#设置字体样式
		            doc.styles["Normal"].font.size = Pt(14)#设置字体大小
		            doc.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'微软雅黑')#设置文档的基础样式
		            doc.add_paragraph(t)#增加一个paragraph,写入内容
		            doc.save(docx_path)#保存文档    
		    except Exception as e:
		        print (e)
		    finally:
		        pass
		print ('数据写入完成')
def r(dir_str,file_list,b):
	getResult=get_result(dir_str,file_list,b)
	getResult.get_image()
	getResult.insert_word()
if __name__=="__main__"::
	dir_str='{0}.docx'#文件名称
	file_list={
	'201310',
	'201410',
	'201510'
	}	
	b=os.getcwd()#当前文件地址,可传入固定字符串,格式为:C:\\Test\\a
	r(dir_str,file_list,b)
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐