【问题标题】:PDF to text convert using python pytesseract使用 python pytesseract 将 PDF 转换为文本
【发布时间】:2021-04-07 23:17:22
【问题描述】:

我正在尝试将许多 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.glob
  • 感谢@Tim Roberts。现在我收到此错误PDFPageCountError: Unable to get page count. I/O Error: Couldn't open file 'K:\pdf_files': No error.
  • 谢谢@aneroid 仍然收到错误PDFPageCountError: Unable to get page count. I/O Error: Couldn't open file '000020051-20140528122047.pdf': No error. 现在它无法打开pdf文件

标签: python python-3.x pdf python-tesseract


【解决方案1】:

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

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

另外,不要不断地附加到 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)

【讨论】:

  • 谢谢@aneroid。但我既没有收到任何错误,也没有收到任何 pdf 文件的转换。但正如我所提到的,代码一次只能在一个目录上运行。
  • 一件事可能与指定以 .pdf 结尾的文件有关,但我不知道该怎么做。
  • 添加了一个检查以跳过非 PDF 文件
  • from the docs 您可能需要添加一个输出文件夹/路径。
  • 谢谢,我目前正在这样做r"K:\converted\*\*.pdf",正如我在以下答案中所建议的那样。这更容易。欣赏它。
【解决方案2】:

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

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-13
    • 1970-01-01
    • 1970-01-01
    • 2018-01-10
    • 2013-07-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多