使用python pytesseract将PDF转换为文本

2024-03-28 13:37:04 发布

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

我正在尝试将许多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)

Tags: 文件topath代码infromimportgt
2条回答

正如评论中提到的,您需要的是^{},而不是glob.globos.walk递归地为您提供目录列表pdf_path是当前列出的父目录,dirs是目录/文件夹列表,files是该文件夹中的文件列表

使用^{}使用父文件夹和文件名形成完整路径

另外,与其不断地附加到txt文件,不如在“从页面到文本”循环之外创建它

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)

相关问题 更多 >