首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何从段落python docx中获取图像(inlineshape)

如何从段落python docx中获取图像(inlineshape)
EN

Stack Overflow用户
提问于 2018-04-12 23:40:46
回答 1查看 3.3K关注 0票数 4

我想逐段阅读docx文档,如果有图片(InlineShape),则使用周围的文本对其进行处理。函数Document.inline_shapes将给出文档中所有内联形状的列表。但我想要的是当前段落中出现的那个,如果存在的话...

下面是一个代码示例:

代码语言:javascript
复制
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()

(这是我想要保存这些图片的方式)

EN

回答 1

Stack Overflow用户

发布于 2018-04-19 06:30:20

假设您的段落是par,您可以使用以下代码来查找图像

代码语言:javascript
复制
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
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49800705

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档