烧瓶呈现一个词云

时间:2018-05-09 20:32:14

标签: python matplotlib flask

我正在尝试渲染一个wordcloud,我可以在没有烧瓶的计算机上运行。

我正在使用this question as a base

路线

@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')

模板

{% 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

第二个问题,我得到一张空白图片,所以我不确定如何将wordcloud写入缓冲区。

1 个答案:

答案 0 :(得分:0)

wordcloud constexpr方法创建一个PIL对象,所以你只需要调用PIL的to_image方法。

save