我想逐段阅读docx文档,如果有图片(InlineShape),则使用周围的文本对其进行处理。函数Document.inline_shapes将给出文档中所有内联形状的列表。但我想要的是当前段落中出现的那个,如果存在的话...
下面是一个代码示例:
from docx import Document
doc = Document("test.docx")
blip = doc.inline_shapes[0]._inline.graphic.graphicData.pic.blipFill.blip
rID = blip.embed
document_part = doc.part
image_part = document_part.related_parts[rID]
fr = open("test.png", "wb")
fr.write(image_part._blob)
fr.close()
(这是我想要保存这些图片的方式)
发布于 2018-04-18 22:30:20
假设您的段落是par,您可以使用以下代码来查找图像
import xml.etree.ElementTree as ET
def hasImage(par):
"""get all of the images in a paragraph
:param par: a paragraph object from docx
:return: a list of r:embed
"""
ids = []
root = ET.fromstring(par._p.xml)
namespace = {
'a':"http://schemas.openxmlformats.org/drawingml/2006/main", \
'r':"http://schemas.openxmlformats.org/officeDocument/2006/relationships", \
'wp':"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"}
inlines = root.findall('.//wp:inline',namespace)
for inline in inlines:
imgs = inline.findall('.//a:blip', namespace)
for img in imgs:
id = img.attrib['{{{0}}}embed'.format(namespace['r'])]
ids.append(id)
return ids
https://stackoverflow.com/questions/49800705
复制相似问题