对于初学者或已经使用Python的开发者来说,生成词云图是一个很有趣的项目。但是当你生成好词云图后,你是否知道该如何展示或保存它呢?本篇文章将从多个方面来详细阐述Python生成词云图片在哪儿看。
一、Matplotlib展示词云图
Matplotlib是Python中的一个常用可视化库,它可以用来展示生成好的词云图。在这里,我们首先生成一个词云图:
import numpy as np import jieba from wordcloud import WordCloud import matplotlib.pyplot as plt # 读取文本 text = open('text.txt', 'r', encoding='utf-8').read() # 分词 words = jieba.cut(text) # 拼接词语 result = ' '.join(words) # 设置词云参数 wc = WordCloud( font_path='SimHei.ttf', background_color='white', max_words=200, max_font_size=100 ) # 生成词云 cloud = wc.generate(result) # 展示词云图 plt.imshow(cloud) plt.axis('off') plt.show()
在上述代码中,我们使用Matplotlib中的imshow()
函数来展示生成好的词云图,并使用axis()
函数来隐藏坐标轴。
二、生成图片保存到本地
如果你想要将生成的词云图保存到本地,可以使用Pillow库的Image模块:
from PIL import Image # 生成图片 image = cloud.to_image() # 保存图片到本地 image.save('wordcloud.png')
在上述代码中,我们使用to_image()
函数将生成好的词云图转化为PIL库中的Image对象,并使用save()
函数将图片保存到本地。
三、生成HTML页面展示
如果你想要在网页上展示生成好的词云图,可以使用Flask搭建一个简单的Web应用。
from flask import Flask, render_template, send_file app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/wordcloud') def wordcloud(): # 读取文本 text = open('text.txt', 'r', encoding='utf-8').read() # 分词 words = jieba.cut(text) # 拼接词语 result = ' '.join(words) # 设置词云参数 wc = WordCloud( font_path='SimHei.ttf', background_color='white', max_words=200, max_font_size=100 ) # 生成词云 cloud = wc.generate(result) # 保存图片到本地 cloud.to_file('static/wordcloud.png') return send_file('static/wordcloud.png', mimetype='image/png') if __name__ == '__main__': app.run()
在上述代码中,我们首先创建了一个Flask应用,使用@app.route()
装饰器定义了两个路由:用于渲染HTML页面的index()
函数和用于生成词云图并返回图片文件的wordcloud()
函数。在wordcloud()
函数中,我们先根据文本生成词云图,然后使用to_file()
函数将词云图保存到本地的静态文件夹中,最后使用send_file()
函数返回图片文件。
四、使用WordCloud在线展示
如果你想要在线展示生成好的词云图,可以使用WordCloud的在线展示功能。首先在终端中安装WordCloud模块:
pip install wordcloud[wordcloud-demos]
然后在代码中使用WordCloud的show()
函数就可以在浏览器中在线展示生成的词云图:
from wordcloud import WordCloud # 读取文本 text = open('text.txt', 'r', encoding='utf-8').read() # 分词 words = jieba.cut(text) # 拼接词语 result = ' '.join(words) # 设置词云参数 wc = WordCloud( font_path='SimHei.ttf', background_color='white', max_words=200, max_font_size=100 ) # 生成词云 cloud = wc.generate(result) # 在线展示词云图 cloud.show()
在上述代码中,我们使用show()
函数在线展示生成好的词云图。