[英]Extract images from word document using Python
如何使用 python 从 word 文档中提取图像/徽标并将它们存储在文件夹中。 以下代码将 docx 转换为 html,但它不会从 html 中提取图像。 任何指针/建议都会有很大帮助。
profile_path = <file path>
result=mammoth.convert_to_html( profile_path)
f = open(profile_path, 'rb')
b = open(profile_html, 'wb')
document = mammoth.convert_to_html(f)
b.write(document.value.encode('utf8'))
f.close()
b.close()
您可以使用docx2txt库,它会读取您的 .docx 文档并将图像导出到您指定的目录(必须存在)。
!pip install docx2txt
import docx2txt
text = docx2txt.process("/path/your_word_doc.docx", '/home/example/img/')
执行后,您将在/home/example/img/ 中获得图像,而变量text将具有文档文本。 它们将按外观顺序命名为 image1.png ... imageN.png。
注意:Word 文档必须为 .docx 格式。
import docx2txt
#extract text
text = docx2txt.process(r"filepath_of_docx")
#extract text and write images in Temporary Image directory
text = docx2txt.process(r"filepath_of_docx",r"Temporary_Image_Directory")
import aspose.words as aw
# load the Word document
doc = aw.Document(r"filepath")
# retrieve all shapes
shapes = doc.get_child_nodes(aw.NodeType.SHAPE, True)
imageIndex = 0
# loop through shapes
for shape in shapes :
shape = shape.as_shape()
if (shape.has_image) :
# set image file's name
imageFileName = f"Image.ExportImages.{imageIndex}_{aw.FileFormatUtil.image_type_to_extension(shape.image_data.image_type)}"
# save image
shape.image_data.save(imageFileName)
imageIndex += 1
查看Alderven 在使用 python 提取 docx 文件中的所有图像的答案
zipfile
适用于比docx2txt
更多的图像格式。 例如,EMF 图像不能通过docx2txt
提取,但可以通过zipfile
提取。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.