在lambda中从s3读取doc、docx文件。

问题描述 投票:0回答:1

TLDR; 用我的AWS lambda阅读 doc, docx 存储在S3上的文件。

在我的本地机器上,我只用 textract.process(file_path) 来同时读取doc和docx文件。

所以在lambda上做同样的事情,直观的方法是将文件从s3下载到本地存储(tmp)上的lambda,然后再处理该 tmp 就像我在本地机器上做的那样

这样不划算...

有没有办法把S3对象直接做成一个管道,让它进入一些解析器,比如 textract 那只会把 docdocx 文件变成一个可读对象,如 string?

我的代码到目前为止,阅读文件如txt。

import boto3

print('Loading function')


def lambda_handler(event, context):
    try:  # Read s3 file
        bucket_name = "appsresults"
        download_path = 'Folder1/file1.txt'
        filename = download_path
        s3 = boto3.resource('s3')
        content_object = s3.Object(bucket_name, filename)        

        file_content = content_object.get()['Body'].read().decode('utf-8')

        print(file_content)

    except Exception as e:
        print("Couldnt read the file from s3 because:\n {0}".format(e))

    return event  # return event
python amazon-s3 aws-lambda docx doc
1个回答
-1
投票

这个答案解决了一半的问题

textract.process 目前不支持读取类文件对象. 如果是这样,你可以直接将文件从S3加载到内存中,然后传给 process 功能。

旧版的 textract 内用 python-docx 阅读包 .docx 文件。python-docx 支持阅读 类文件 对象。你可以使用下面的代码来实现你的目标,至少对于 .docx 文件。

import boto3
import io
from docx import Document

s3 = boto3.resource('s3')
bucket = s3.Bucket('my-bucket')
object = bucket.Object('/files/resume.docx')

file_stream = io.BytesIO()
object.download_fileobj(file_stream)

document = docx.Document(file_stream)
© www.soinside.com 2019 - 2024. All rights reserved.