首页 > 解决方案 > 使用 python 从 pdf 文件中生成 .txt 文件,名称与 pdf 中的名称相同

问题描述

我有一个包含 pdf 文件的目录。当您将文件名传递给 wand.image 类的对象时,我编写了执行 OCR 的代码。我现在要做的是遍历pdf文件的目录并为每个pdf生成一个OCR'd txt文件并将其保存在某个目录中。我写到现在的代码如下:

import io
from PIL import Image
import pytesseract
from wand.image import Image as wi




pdf = wi(filename = r"D:\files\aba7d525-04b8-4474-a40d-e94f9656ed42.pdf", resolution = 300)

pdfImg = pdf.convert('jpeg')

imgBlobs = []

for img in pdfImg.sequence:
    page = wi(image = img)
    imgBlobs.append(page.make_blob('jpeg'))

extracted_text = []

for imgBlob in imgBlobs:
    im = Image.open(io.BytesIO(imgBlob))
    text = pytesseract.image_to_string(im, lang = 'eng')
    extracted_text.append(text)

print(extracted_text[0])

问题是,如果您看到我的代码(“pdf = ..”),我已经在代码中硬编码了一个文件名,但我需要在那里传递一个目录,以便该目录中的所有文件都可以进行 OCR 处理,而且我需要将所有这些文件及其文件名作为输出,仅将 .pdf 替换为 .txt。我怎样才能做到这一点

标签: pythonloopsocrfile-handlingfile-generation

解决方案


您可以使用 glob

例子:

import os
import glob
from wand.image import Image as wi

files = glob.glob("D:\files\*")

for file in files:
    pdf = wi(filename = file, resolution = 300)
    # write your code
    with open("D:\extracted_files\" + os.path.split(file)[-1].split(".")[0] + ".txt", 'w') as f:
        f.write(extracted_text)

推荐阅读