1 python
我如何找到文档文件中存在的图像图像,python中是否有用于此的任何模块。我搜索了但没有用。这就是我们可以从Word文件读取的方式。下面的代码不提供有关文件中存在的图像的信息
from docx import Document
documnet=Document('new-file-name.docx')
para=documnet.paragraphs
for par in para:
print par.text
Run Code Online (Sandbox Code Playgroud)
由于.docx文件是zip文件,因此可以使用zipfile模块:
import zipfile
z = zipfile.ZipFile("1.docx")
#print list of valid attributes for ZipFile object
print dir(z)
#print all files in zip archive
all_files = z.namelist()
print all_files
#get all files in word/media/ directory
images = filter(lambda x: x.startswith('word/media/'), all_files)
print images
#open an image and save it
image1 = z.open('word/media/image1.jpeg').read()
f = open('image1.jpeg','wb')
f.write(image1)
#Extract file
z.extract('word/media/image1.jpeg', r'path_to_dir')
Run Code Online (Sandbox Code Playgroud)
您必须首先将所有图像文件解压缩为 .zip,在 XML 代码中查找图像元素并将每个图像与其 rId 相关联。
import os
import docx
import docx2txt
# Extract the images to img_folder/
docx2txt.process('document.docx', 'img_folder/')
# Open you .docx document
doc = docx.Document('document.docx')
# Save all 'rId:filenames' relationships in an dictionary named rels
rels = {}
for r in doc.part.rels.values():
if isinstance(r._target, docx.parts.image.ImagePart):
rels[r.rId] = os.path.basename(r._target.partname)
# Then process your text
for paragraph in doc.paragraphs:
# If you find an image
if 'Graphic' in paragraph._p.xml:
# Get the rId of the image
for rId in rels:
if rId in paragraph._p.xml:
# Your image will be in os.path.join(img_path, rels[rId])
else:
# It's not an image
Run Code Online (Sandbox Code Playgroud)
GitHub 存储库链接:django-docx-import