我不想用python写和读同一个文档



我有pdf文件,我想从第一页提取信息。我的解决方案是:

  1. 使用PyPDF2从S3读取并只保存第一页。
  2. 读取我保存的相同的一页pdf,转换为字节64并在AWS文本上分析它。

它工作,但我不喜欢这个解决方案。保存和读取完全相同的文件有什么必要呢?我可以不直接在运行时使用该文件吗?

这是我不喜欢做的事情:

from PyPDF2 import PdfReader, PdfWriter
from io import BytesIO
import boto3
def analyse_first_page(bucket_name, file_name):
s3 = boto3.resource("s3")
obj = s3.Object(bucket_name, file_name)
fs = obj.get()['Body'].read()
pdf = PdfReader(BytesIO(fs), strict=False)
writer = PdfWriter()
page = pdf.pages[0]
writer.add_page(page)

# Here is the part I do not like
with open("first_page.pdf", "wb") as output:
writer.write(output)
with open("first_page.pdf", "rb") as pdf_file:
encoded_string = bytearray(pdf_file.read())
#Analyse text
textract = boto3.client('textract')
response = textract.detect_document_text(Document={"Bytes": encoded_string})
return response
analyse_first_page(bucket, file_name)

没有AWS方法可以做到这一点吗?就没有更好的办法了吗?

您可以使用BytesIO作为内存中的流,而不需要写入文件,然后再读取。

with BytesIO() as bytes_stream:
writer.write(bytes_stream)
bytes_stream.seek(0)
encoded_string = b64encode(bytes_stream.getvalue())

相关内容