【发布时间】:2020-07-09 01:25:51
【问题描述】:
我是 Python 和一般编码的新手。我正在尝试创建一个程序,该程序将 OCR 一个 PDF 目录然后提取文本,以便我以后可以挑选出特定的东西。但是,我无法让 pdfPlumber 从所有页面中提取所有文本。您可以从头到尾进行索引,但如果结尾未知,则会因为索引超出范围而中断。
import ocrmypdf
import os
import requests
import pdfplumber
import re
import logging
import sys
import PyPDF2
## test folder C:\Users\adams\OneDrive\Desktop\PDF
user_direc = input("Enter the path of your files: ")
#walks the path and prints out each PDF in the
#OCRs the documents and skips any OCR'd pages.
for dir_name, subdirs, file_list in os.walk(user_direc):
logging.info(dir_name + '\n')
os.chdir(dir_name)
for filename in file_list:
file_ext = os.path.splitext(filename)[0--1]
if file_ext == '.pdf':
full_path = dir_name + '/' + filename
print(full_path)
result = ocrmypdf.ocr(filename, filename, skip_text=True, deskew = True, optimize = 1)
logging.info(result)
#the next step is to extract the text from each individual document and print
directory = os.fsencode(user_direc)
for file in os.listdir(directory):
filename = os.fsdecode(file)
if filename.endswith('.pdf'):
with pdfplumber.open(file) as pdf:
page = pdf.pages[0]
text = page.extract_text()
print(text)
按原样,这只会从每个 PDF 的第一页获取文本。我想从每个 PDF 中提取所有文本,但如果我的索引太大并且我不知道 PDF 的页数,pdfPlumber 会中断。 我试过了
page = pdf.pages[0--1]
但这也会中断。我也找不到使用 PyPDF2 的解决方法。如果此代码草率或不可读,我深表歉意。我尝试添加 cmets 来解释我在做什么。
【问题讨论】: