【问题标题】:How to get an image (inlineshape) from paragraph python docx如何从段落python docx获取图像(inlineshape)
【发布时间】:2019-01-09 01:36:10
【问题描述】:

我想逐段阅读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()

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

【问题讨论】:

    标签: python-3.x image docx python-docx


    【解决方案1】:

    假设您的段落是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
    

    【讨论】:

    • 试过for par in document.paragraphs: hasImage(par),它返回:NameError: name 'ET' is not defined。你知道ET应该怎么定义吗?
    • 应该是import xml.etree.ElementTree as ET
    • 如果您的解释器是 python2,则在将 xml 发送到 ET.fromstring 方法之前将其编码为“utf8”,以避免编码错误
    猜你喜欢
    • 2015-05-28
    • 1970-01-01
    • 2015-03-25
    • 1970-01-01
    • 2014-08-20
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多