我有一个docx文件,其中包含6-7个图像。我需要自动从这个文档文件中提取图像。有没有类似的win32com
ms word API?或者任何可以准确提取其中所有图像的库?
这是我尝试过的,但问题首先是它没有给我所有的图像,其次它给了我许多错误的图像,比如空白图像,非常小的图像,线条等。它也使用MS word来做同样的事情。
from pathlib import Path
from win32com.client import Dispatch
xls = Dispatch("Excel.Application")
doc = Dispatch("Word.Application")
def export_images(fp, prefix="img_", suffix="png"):
""" export all of images(inlineShapes) in the word file.
:param fp: path of word file.
:param prefix: prefix of exported images.
:param suffix: suffix of exported images.
"""
fp = Path(fp)
word = doc.Documents.Open(str(fp.resolve()))
sh = xls.Workbooks.Add()
for idx, s in enumerate(word.inlineShapes, 1):
s.Range.CopyAsPicture()
d = sh.ActiveSheet.ChartObjects().add(0, 0, s.width, s.height)
d.Chart.Paste()
d.Chart.Export(fp.parent / ("%s_%s.%s" % (prefix, idx, suffix))
sh.Close(False)
word.Close(False)
export_images(r"C:\Users\HPO2KOR\Desktop\Work\venv\us2017010202.docx")
你可以在这里下载docx文件https://drive.google.com/open?id=1xdw2MieI1n3ulXlkr
发布于 2020-02-13 14:45:04
你可以从docx
解压所有的图片,预先按大小过滤:
import zipfile
archive = zipfile.ZipFile('file.docx')
for file in archive.filelist:
if file.filename.startswith('word/media/') and file.file_size > 300000:
archive.extract(file)
在your example中,可以找到5
图像:
发布于 2020-02-13 14:16:33
在枚举循环中,您可能应该检查形状类型是否为图片:
for idx, s in enumerate(word.inlineShapes, 1):
if s.Type != 3: # wdInlineShapePicture
continue
# ...
发布于 2020-02-13 16:32:36
添加另一种方法来做同样的事情。我们可以使用doc2txt
库来获取所有的图像
import docx2txt
text = docx2txt.process("docx_file", r"directory where you want to store the images")
注意,它还在text变量中给出了在文件中找到的所有文本。
https://stackoverflow.com/questions/60201419
复制相似问题