【问题标题】:saving wordcloud plot from AWS lambda to S3 bucket将 wordcloud 图从 AWS lambda 保存到 S3 存储桶
【发布时间】:2021-05-01 16:01:19
【问题描述】:

我目前正在尝试将我在 AWS lambda 函数中生成的词云保存到我的 s3 存储桶中,我的代码执行gut给出“errorMessage”:“参数验证失败:\n参数正文的类型无效,值:,类型:,有效类型:, , file-like object",

作为一个错误,我上网查了一下似乎找不到原因,我是否需要将绘图转换为字节才能像这样将其存储在 S3 中?

from wordcloud import WordCloud, STOPWORDS
import matplotlib.pyplot as plt
import boto3

text = "cat cat cat dog dog dog test test hello one two three four five"
generate_word_cloud(text)


def generate_word_cloud(text):
    wordcloud = WordCloud(width = 3000, 
                        height = 2000, 
                        random_state=1, 
                        background_color='salmon', 
                        colormap='Pastel1', 
                        collocations=False, 
                        stopwords = STOPWORDS).generate(text)
    save_to_bucket(wordcloud)


def save_to_bucket(wordcloud):
    #Save tweet list to an s3 bucket
    BUCKET_NAME = "1706224-tweets"
    FILE_NAME = "wordcloud.png"
    s3 = boto3.resource('s3')
    object = s3.Object(BUCKET_NAME, FILE_NAME)
    object.put(Body=wordcloud)

【问题讨论】:

标签: python amazon-web-services matplotlib amazon-s3 aws-lambda


【解决方案1】:

您可以将 PIL 图像转换为字节数组并使用它,例如,在您的情况下,您可以在 save_to_bucket 方法中执行以下操作


def save_to_bucket(wordcloud):
    #Save tweet list to an s3 bucket
    BUCKET_NAME = "1706224-tweets"
    FILE_NAME = "wordcloud.png"
    s3 = boto3.resource('s3')
    object = s3.Object(BUCKET_NAME, FILE_NAME)

    // here you convert the PIL image that generate wordcloud to byte array
    image_byte = image_to_byte_array(wordcloud.to_image())
    object.put(Body=image_byte)


def image_to_byte_array(image: Image, format: str = 'png'):
    result = io.BytesIO()
    image.save(result, format=format)
    result = result.getvalue()

    return result

【讨论】:

    【解决方案2】:

    最后我使用lambda的/tmp存储来临时存储图像,然后上传图像

    wordcloud.to_file("/tmp/"+FILE_NAME)
    s3 = boto3.client('s3')
    s3.upload_file("/tmp/"+FILE_NAME,BUCKET_NAME,FILE_NAME)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-21
      • 1970-01-01
      • 1970-01-01
      • 2020-09-15
      • 1970-01-01
      • 2020-12-22
      • 1970-01-01
      相关资源
      最近更新 更多