使用 python pytesseract 将 PDF 转换为文本

PDF to text convert using python pytesseract

我正在尝试将许多 pdf 文件转换为 txt。我的 pdf 文件组织在目录中的子目录中。所以我有三层:目录 --> 子目录 --> 每个子目录中的多个 pdf 文件。我正在使用以下代码,它给了我这个错误 ValueError: too many values to unpack (expected 3)。当我转换单个目录中的文件而不是多个子目录中的文件时,代码有效。

它可能很简单,但我无法理解它。任何帮助将非常感激。谢谢

import pytesseract
from pdf2image import convert_from_path
import glob

pdfs = glob.glob(r"K:\pdf_files")

for pdf_path, dirs, files in pdfs:
    for file in files:
    convert_from_path(os.path.join(pdf_path, file), 500)

        for pageNum,imgBlob in enumerate(pages):
            text = pytesseract.image_to_string(imgBlob,lang='eng')

            with open(f'{pdf_path}.txt', 'a') as the_file:
                the_file.write(text)

如评论中所述,您需要 os.walk,而不是 glob.globos.walk 递归地为您提供目录列表。 pdf_path 是它当前列出的父目录,dirs 是 directories/folders 的列表,files 是该文件夹中的文件列表。

使用 os.path.join() 使用父文件夹和文件名形成完整路径。

此外,不要不断地附加到 txt 文件,只需在 'page-to-text' 循环之外创建它。

import os

pdfs_dir = r"K:\pdf_files"

for pdf_path, dirs, files in os.walk(pdfs_dir):
    for file in files:
        if not file.lower().endswith('.pdf'):
            # skip non-pdf's
            continue
        
        file_path = os.path.join(pdf_path, file)
        pages = convert_from_path(file_path, 500)
        
        # change the file extension from .pdf to .txt, assumes
        # just one occurrence of .pdf in the name, as the extension
        with open(f'{file_path.replace(".pdf", ".txt")}', 'w') as the_file:  # write mode, coz one time
            for pageNum, imgBlob in enumerate(pages):
                text = pytesseract.image_to_string(imgBlob,lang='eng')
                the_file.write(text)

我刚刚通过添加*指定目录中的所有子目录以更简单的方式解决了问题:

import pytesseract
from pdf2image import convert_from_path
import glob

pdfs = glob.glob(r"K:\pdf_files\*\*.pdf")

for pdf_path in pdfs:
    pages = convert_from_path(pdf_path, 500)

    for pageNum,imgBlob in enumerate(pages):
        text = pytesseract.image_to_string(imgBlob,lang='eng')

        with open(f'{pdf_path}.txt', 'a') as the_file:
            the_file.write(text)