python - 从 MS Word 中的表格中识别图像文件

标签 python python-docx

我使用 docx python 库读取了一个 MS-Word 文件。 word 文件包含表(表中只有 1 列),如 table1、table2 等。我需要逐表阅读。每当一行有一个或多个图片文件时,我需要在表#和行#中显示“找到图像文件”

这是我所做的。 docx api 的 inline_shapes 属性 给出了找到的图像文件的对象列表。但它没有指定找到图像的表号和行号。

from docx.api import Document

doc = Document("demo.docx")

for image in doc.inline_shapes:
    print(image)

for table in doc.tables:
    for row in table.rows:
        for cell in row.cells:
            print(cell.text) # it prints only the text and no info about image

一些有用的引用资料

python docx how to read text along with inline images?

Finding image present docx file using python

最佳答案

python-docx 还不能很好地支持这种情况,但这里有一种解决方法:

from docx.api import Document

doc = Document("demo.docx")

for table_index, table in enumerate(doc.tables):
    for row_index, row in enumerate(table.rows):
        for cell_index, cell in enumerate(row.cells):
            blips = cell._element.xpath('*/*/*/*/*/*/*/*/a:blip')
            if type(blips) is list:
                for blip in blips:
                    # sample output:
                    # table[12] row[2] cell[0] link_to_image[rId17]
                    print('table[{}] row[{}] cell[{}] link_to_image[{}]'
                          .format(table_index, row_index, cell_index, blip.embed))

                    # write to file
                    image_part = doc.part.related_parts[blip.embed]
                    with open('demo.png', 'wb') as f:
                        f.write(image_part.blob)

不理想,但可以解决问题。

关于python - 从 MS Word 中的表格中识别图像文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49666591/

相关文章:

python - 安装 Pillow 时出错 --enable-jpeg 已请求但未找到 jpeg

python - 通过 Python 和 SUDS 访问 Kashoo API。身份验证 token 中的时间格式问题

python - CTYPES 和 PYTHON3 : Can't return long string

python-docx 如何合并行单元格

python - 使用 python-docx 插入图像后,Word 文档的表格单元格中出现空行

python - 如何在 MS Windows 操作系统上使用 Google 的 repo 工具?

python - 使用 python-docx 迭代 docx 中的目录

python - 无法使用Python-docx获取Word中ContentControl中的文本

python - TypeError : 'dict' object is not callable

python - 选择具有存储值的页面元素