首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Flask渲染单词云

Flask渲染单词云
EN

Stack Overflow用户
提问于 2018-05-10 04:32:14
回答 1查看 1.7K关注 0票数 0

我正在尝试渲染一个可以在没有flask的情况下在我的计算机上运行的wordcloud。

我正在使用this question as a base

路由

代码语言:javascript
复制
@app.route('/wordcloud/<vendor_duns>')
def images(vendor_duns):
    words = Words.query.filter(Words.vendor_duns == vendor_duns).with_entities(Words.words).all()
    # t = [r.__dict__ for r in words]
    # print(t)
    one_row = list(itertools.chain.from_iterable(words))
    text = ' '.join(one_row)
    return render_template("wordcloud.html", text=text)


@app.route('/fig/<vendor_duns>')
def fig(vendor_duns):
    # TODO add test model and query
    words = Words.query.filter(Words.vendor_duns == vendor_duns).with_entities(Words.words).all()
    one_row = list(itertools.chain.from_iterable(words))
    text = ' '.join(one_row)
    wordcloud = WordCloud().generate(text)
    plt.imshow(wordcloud, interpolation='bilinear')
    plt.axis("off")
    img = BytesIO()
    plt.savefig(img)
    img.seek(0)
    return send_file(img, mimetype='image/png')

模板

代码语言:javascript
复制
{% extends "base.html" %}

{% block title %}Wordcloud{% endblock %}
{% block content %}  
{{text}}
    <div>
      <img src="{{ url_for('sam.fig', vendor_duns=vendor_duns) }}" alt="Image Placeholder" height="100">
    </div>
{% endblock %}

首先,模板中的{{text}}只是为了查看。如果我导航到一个特定的vendor_duns,我会得到一个很长的文本字符串,但没有图像。

那么有两个问题,我到底需要在哪里运行查询?在fig或图像function中。

第二个问题是,我得到了一个空白图像,所以我不确定如何将单词云写入缓冲区。

EN

回答 1

Stack Overflow用户

发布于 2018-05-10 07:24:23

wordcloud to_image方法创建了一个PIL对象,因此您所要做的就是调用PIL的save方法。

代码语言:javascript
复制
img = BytesIO()
wordcloud.to_image().save(img, 'PNG')
img.seek(0)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50261578

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档