python如何提取word内的图片


 

 

解压.docx文件实现提取图片

前言

.docx文件其实也就是一个压缩文件,当我们将一个.docx文件直接解压后可以看到如下目录

 其中我们要找的图片就在word/media目录内,如图

所以,要提取word内的图片就需要将.docx文件解压,再从media文件内取得图片,然后将解压后的文件删除

代码实现

import  os
import  shutil
import  zipfile
 
 
def  get_pictures(word_path, result_path):
     """
     获取word内的所有图片
     :param word_path: word文件
     :param result_path: 结果目录,无需手动创建
     :return: None or generator,None:word内没有图片,generator:每个图片的路径
     """
     tmp_path =  f '{os.path.splitext(word_path)[0]}'
     # 拷贝源文件后重命名再解压
     splitext =  os.path.splitext(word_path)
     zip_path =  shutil.copy(word_path, f '{splitext[0]}_new{splitext[1]}' )
     with zipfile.ZipFile(zip_path, 'r' ) as f:
         for  file  in  f.namelist():
             f.extract( file , tmp_path)
     os.remove(zip_path)
     # 注:word图片在zip文件内的word/media目录下
     pic_path =  os.path.join(tmp_path, 'word/media' )
     if  not  os.path.exists(pic_path):
         shutil.rmtree(tmp_path)
         return  'no pictures found'
     pictures =  os.listdir(pic_path)
     if  not  os.path.exists(result_path):
         os.makedirs(result_path)
     for  picture in  pictures:
         # 根据word的文件名生成图片的名称
         word_name =  os.path.splitext(word_path)[ 0 ]
         if  os.sep in  word_name:
             new_name =  word_name.split( '\\' )[ - 1 ]
         else :
             new_name =  word_name.split( '/' )[ - 1 ]
         picture_name =  f '{new_name}_{picture}'
         shutil.copy(os.path.join(pic_path, picture), os.path.join(result_path, picture_name))
 
     shutil.rmtree(tmp_path)
     return  (os.path.join(result_path, pic) for  pic in  os.listdir(result_path))

word_path可以支持所有类型路径,如

p =  r "C:\Users\Desktop\test\小说.docx"
p1 =  "C:/Users/Desktop/test/小说.docx"
p2 =  "C:\\Users\\Desktop\\test\\小说.docx"

利用三方库docx实现图片提取(推荐)

import  docx
import  os, re
 
 
def  get_pictures(word_path, result_path):
     """
     图片提取
     :param word_path: word路径
     :param result_path: 结果路径
     :return:
     """
     doc =  docx.Document(word_path)
     dict_rel =  doc.part._rels
     for  rel in  dict_rel:
         rel =  dict_rel[rel]
         if  "image"  in  rel.target_ref:
             if  not  os.path.exists(result_path):
                 os.makedirs(result_path)
             img_name =  re.findall( "/(.*)" , rel.target_ref)[ 0 ]
             word_name =  os.path.splitext(word_path)[ 0 ]
             if  os.sep in  word_name:
                 new_name =  word_name.split( '\\' )[ - 1 ]
             else :
                 new_name =  word_name.split( '/' )[ - 1 ]
             img_name =  f '{new_name}_{img_name}'
             with open (f '{result_path}/{img_name}' , "wb" ) as f:
                 f.write(rel.target_part.blob)


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM