Python 将从每个图像检索到的OCR文本写入对应于每个图像的单独文本文件
我正在阅读一个pdf文件,将每个页面转换为图像并保存,接下来我需要对每个图像运行OCR,识别每个图像文本并将其写入一个新的文本文件Python 将从每个图像检索到的OCR文本写入对应于每个图像的单独文本文件,python,ocr,tesseract,Python,Ocr,Tesseract,我正在阅读一个pdf文件,将每个页面转换为图像并保存,接下来我需要对每个图像运行OCR,识别每个图像文本并将其写入一个新的文本文件 pdf_dir = 'dir path' os.chdir(pdf_dir) for pdf_file in os.listdir(pdf_dir): if pdf_file.endswith(".pdf"): pages = convert_from_path(pdf_file, 300) pdf_file = pdf_f
pdf_dir = 'dir path'
os.chdir(pdf_dir)
for pdf_file in os.listdir(pdf_dir):
if pdf_file.endswith(".pdf"):
pages = convert_from_path(pdf_file, 300)
pdf_file = pdf_file[:-4]
for page in pages:
page.save("%s-page%d.jpg" % (pdf_file,pages.index(page)), "JPEG")
img_dir = 'dir path'
os.chdir(img_dir)
docs = []
for img_file in os.listdir(img_dir):
if img_file.endswith(".jpg"):
texts = str(((pytesseract.image_to_string(Image.open(img_file)))))
text = texts.replace('-\n', '')
print(texts)
img_file = img_file[:-4]
for text in texts:
file = img_file + ".txt"
# create the new file with "w+" as open it
with open(file, "w+") as f:
for texts in docs:
# write each element in my_list to file
f.write("%s" % str(texts))
print(file)
我知道如何从所有图像中获取所有文本并将其转储到一个文本文件中
pdf_dir = 'dir path'
os.chdir(pdf_dir)
for pdf_file in os.listdir(pdf_dir):
if pdf_file.endswith(".pdf"):
pages = convert_from_path(pdf_file, 300)
pdf_file = pdf_file[:-4]
for page in pages:
page.save("%s-page%d.jpg" % (pdf_file,pages.index(page)), "JPEG")
img_dir = 'dir path'
os.chdir(img_dir)
docs = []
for img_file in os.listdir(img_dir):
if img_file.endswith(".jpg"):
texts = str(((pytesseract.image_to_string(Image.open(img_file)))))
text = texts.replace('-\n', '')
print(texts)
img_file = img_file[:-4]
for text in texts:
file = img_file + ".txt"
# create the new file with "w+" as open it
with open(file, "w+") as f:
for texts in docs:
# write each element in my_list to file
f.write("%s" % str(texts))
print(file)
我需要一个文本文件被写入对应于每个图像,其中已识别该图像中的文本。目前编写的文件都是空的,我不知道出了什么问题。有人能帮忙吗?这里有很多东西需要解开:
文档
,这是一个空列表,以创建文本文件,因此,每个文本文件仅被创建(空),而文件.write
永远不会执行text=text.replace('-\n','')
,但是您没有对它做任何事情,而是对文本中的文本进行迭代,因此在该循环中,text
不是replace
的结果,而是iterabletext
中的一项
text
是一个str
,因此text中的每个文本都是一个字符
文本
(以前也指定)作为文档
的迭代器(同样,这是空的)for img_file in os.listdir(img_dir):
if img_file.endswith(".jpg"):
texts = str(((pytesseract.image_to_string(Image.open(img_file)))))
print(texts)
file = img_file[:-4] + ".txt"
#create the new file with "w+" as open it
with open(file, "w+") as f:
f.write(texts)
print(file)
文档
为空列表。您还将text
用作嵌套循环中的迭代器。可能不是一个错误,但可能不是一个好的做法。您可能只希望将open(文件“w+”)作为f:
,然后f.write(“%s”%str(text))
。是的,我意识到我正在创建一个空列表,然后对其进行迭代,因此它会导致空文档。谢谢在li'l试验之后,我得到了代码中相同的更正,感谢您向我解释这四点。这有帮助!非常感谢。干杯@shweta24。我还注意到,text
已经是一个字符串,所以不需要做:f.write(“%s”%str(text))
,你可以做得更简单:f.write(text)
.Yupp,注意:)。谢谢你,大卫!