我使用 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
还不能很好地支持这种情况,但这里有一种解决方法:
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/