我想逐段阅读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()
(这就是我想保存这些图片的方式)
答案 0 :(得分:5)
假设您的段落是标准杆,您可以使用以下代码查找图像
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