使用Python docx2txt从Word文档中提取图像

2024-06-14 17:36:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用docx2txt从相同数量的word文档中提取一组图像(即,每个word文档中都保存了一个图像,没有其他内容;不要问我是如何在这里结束的)。我遇到的问题是,docx2txt中的函数“process”将特定word文件中的第一个图像保存为“image1”,第二个图像保存为“image2”,等等。因为我正在迭代word文档列表,每次它尝试在下一个word文档中查找图像时,都会将其保存在前面标题为“image1”的文件上。我的问题:使用docx2txt包有没有办法避免这个问题?我已经阅读了他们的文档,它非常稀少,似乎没有指明更改您保存的图像文件名称的方法(即,我可以将其保存为列表范围内的n的“image\n”,而不是默认为“image1”)。下面是我的代码。如果您有任何建议/链接,我们将不胜感激

import docx2txt
import os

path ="whatever the path is"
savepath = "wherever one would want to save this"

files = []
for file in os.listdir(path):
    if file.endswith('.docx'):
        files.append(file) 

for i in range(len(files)):
    image = docx2txt.process(path+ "/" +files[i], savepath) ## this is the line that overwrites each new image

我理解它为什么不起作用,但似乎没有其他方法来处理使用此软件包保存图像的问题。再次感谢您的建议

(注:关于这个问题,我已经讨论了其他问题,但他们似乎专注于从一个文档中提取多个图像,而不是从多个文档中提取一个图像。)


Tags: 文件path方法文档图像imageimport列表
2条回答

https://github.com/ankushshah89/python-docx2txt/blob/c94663234d2882aa75932f9c9973eb5a804df13b/docx2txt/docx2txt.py#L72

它指定目录,因此

for i in range(len(files)):
    image = docx2txt.process(path+ "/" +files[i], savepath) ## this is the line that overwrites each new image

您可以指定一个单独的保存路径

for i in range(len(files)):
    savepath=savepath+str(i)
    image = docx2txt.process(path+ "/" +files[i], savepath) ## this is the line that overwrites each new image

我最终的解决方案是:我最终使用以下方法将每个图像保存到与word文档中同样存在的字符串对应的文件夹中:

import docx2txt
import os

path ="path"
savepath = "savepath"

## Collects name information from the word files

files = []
correctedfiles = []
for file in os.listdir(path):
    if file.endswith('.docx'):
        files.append(file)

## Checking above    

for x in range(len(files)):
    print(files[x])

## Makes equal folders as exist questions and names them the by their ID

for i in range(len(files)):
    os.chdir(savepath)
    textresult = docx2txt.process(path + "/" + files[i])
    print(textresult)
    correctresult = textresult.replace('June 2019 ', '')
    os.system('mkdir ' + correctresult)

## Saves images based on name in folders     

for i in range(len(files)):
    textresult = docx2txt.process(path + "/" + files[i])
    correctresult = textresult.replace('June 2019 ', '')
    image = docx2txt.process(path+ "/" +files[i], savepath + '/' + correctresult) 

在word文档的标题(2019年6月)中,有一些额外的位处理多余的单词

相关问题 更多 >