python - 使用 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。我怎样才能做到这一点
解决方案
您可以使用 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)
推荐阅读
- java - while 语句中的无限循环
- c++ - 如何在 C++14 中保留左值引用的同时衰减右值引用类型?
- c - 如何使用正确的 while 循环使文件显示?
- java - 使用 Spring Cloud Circuit Breaker 时避免在 NoFallbackAvailableException 中包装原因
- sql-server - 为 SQL Server 中的数字列选择最佳数据类型
- python - 如何减少在 python 中加载泡菜文件或将泡菜文件映射到磁盘的时间
- html - 如何使用每种颜色类别 HTML/CSS 的空白创建彩色线条?
- matlab - 如何使条形图从空白变为彩色?
- aws-lambda - 使用 Amplify、Stripe Checkout 和 AWS Lambda
- android - Android SurfaceComposerClient