gpt4 book ai didi

python - 为 python 目录中的每个 .pdf 文件创建一个新的 .txt 文件

转载 作者:太空宇宙 更新时间:2023-11-03 20:48:59 25 4
gpt4 key购买 nike

我的代码应该从目录中获取每个 pdf,对其进行 OCR,并为每个 OCR 的 pdf 返回一个 .txt 文件。 pdf 和 .txt 文件的名称应相同,只是 .pdf 更改为 .txt。我陷入了分割输入 pdf 名称以生成具有 .txt 扩展名的 OCR 文件的相同名称的部分。目录中的示例文件如下所示:“000dbf9d-d53f-465f-a7ce-722722136fb7465.pdf”。我需要输出为“000dbf9d-d53f-465f-a7ce-722722136fb7465.txt”。另外,我的代码不会创建新的 .txt 文件,而是在每次迭代时覆盖一个文件。我需要为每个 OCR 的 .pdf 文件创建一个新的 .txt 文件。到目前为止的代码:

import io
import glob
from PIL import Image
import pytesseract
from wand.image import Image as wi


files = glob.glob(r"D:\files\**")
for file in files:
#print(file)
pdf = wi(filename = file, resolution = 300)

pdfImg = pdf.convert('jpeg')

imgBlobs = []

for img in pdfImg.sequence:
page = wi(image = img)
imgBlobs.append(page.make_blob('jpeg'))

extracted_texts = []

for imgBlob in imgBlobs:
im = Image.open(io.BytesIO(imgBlob))
text = pytesseract.image_to_string(im, lang = 'eng')
extracted_texts.append(text)
with open("D:\\extracted_text\\"+ "\\file1.txt", 'w') as f:
f.write(str(extracted_texts))

最佳答案

您只需跟踪您的文件名并在最后两行中重复使用它:

# ...
import os


files = glob.glob(r"D:\files\**")
for file in files:
#print(file)

# Get the name of the file less any suffixes
name = os.path.basename(file).split('.')[0]

# ...

# Use `name` from above to name your text file
with open("D:\\extracted_text\\" + name + ".txt", 'w') as f:
f.write(str(extracted_texts))

关于python - 为 python 目录中的每个 .pdf 文件创建一个新的 .txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56394099/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com