對於初學者或已經使用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()
函數在線展示生成好的詞雲圖。
原創文章,作者:GIRAH,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/374563.html