如何在Python中使用wordcloud庫生成文字雲?
一、安裝和導入wordcloud庫
在使用wordcloud前,需要保證庫已經安裝並導入:
!pip install wordcloud
from wordcloud import WordCloud
二、生成基本的文字雲
首先,你需要提供一個文本文件,對於這個文件我們可以先完成以下幾個步驟:
- 打開文件,並讀取數據。
- 去除文件中的特殊符號和數字,只留下正常文字。
- 將文本序列轉化為字符串形式。
代碼實現如下:
import os
from collections import Counter
import jieba
text = open(os.path.join(d, 'news.txt')).read() #打開文件並讀取數據
c = Counter(text) #可選:觀察數據分佈情況
list(filter(lambda x:x[1]>10,c.items())) #可選:去除較低頻的詞彙
text = ''.join(list(filter(lambda x:x[0] not in ',?!.;『』「」『』%1234567890',text))) #去除特殊符號和數字
text_cut = jieba.cut(text) #使用jieba庫進行分詞
text_cut = ' '.join(list(text_cut))
#生成文字雲
wc = WordCloud(width=800,height=600,mode='RGBA',background_color=None).generate(text_cut)
wc.to_file("wordcloud.png")
運行程序,你將在當前目錄下看到生成的”wordcloud.png”文件。
三、設計文字雲的基本參數
wordcloud庫提供了許多參數,可以對生成的文字雲進行基礎的調整。下面介紹幾個常見的參數。
- background_color: 設定背景顏色,默認為黑色。
- width: 文字雲的寬度,默認為400像素。
- height:文字雲的高度,默認為200像素。
- max_words: 文字雲中的最大詞數,默認為200。
- font_path: 字體路徑,用於設置字體。例如,’STHeiti Medium.ttc’ 或者 ‘/System/Library/Fonts/PingFang.ttc’
代碼示例:
font_path = '/System/Library/Fonts/PingFang.ttc'
wc = WordCloud(
background_color='#E6E6FA',
width=800, height=600,
font_path=font_path,
max_words=500).generate(text_cut)
wc.to_file("wordcloud.png")
四、美化文字雲
如果只是簡單地生成文字雲,效果往往不盡人意。接下來,我們可以從以下幾個方面對文字雲進行美化。
1. 修改字體顏色和形狀
通過 WordCloud()實例中的 color_func 和 mask參數可以實現。
import numpy as np
from PIL import Image
mask = np.array(Image.open(os.path.join(d, "mask.png"))) # mask為透明png或JPEG圖片
wc = WordCloud(
width=800, height=600,
max_words=400,
background_color=None,
mode='RGBA',
font_path=font_path,
mask=mask,
).generate(text)
def grey_color_func(word, font_size, position, orientation, random_state=None, **kwargs):
return "hsl(0, 0%%, %d%%)" % np.random.randint(60, 100)
wc.recolor(color_func=grey_color_func)
wc.to_file("wordcloud.png")
2. 調整字體大小
可以通過 WordCloud()實例中的relative_scaling參數調整。
relative_scaling:浮點數,按照詞頻調整字體大小。
wc = WordCloud(
background_color='#F0F8FF',
font_path=font_path,
width=800,height=600,
max_words=200,
relative_scaling=0.5
).generate(text_cut)
3. 自定義停用詞
使用stopwords參數即可,其中每個元素用逗號分隔。
stopwords = set(jieba.cut(open(os.path.join(d, 'stopwords.txt')).read()))
wc = WordCloud(
background_color='#F0F8FF',
font_path=font_path,
width=800,height=600,
max_words=200,
relative_scaling=0.5,
stopwords=stopwords
).generate(text_cut)
五、總結
Python wordcloud庫可以幫助我們生成精美的文字雲,能夠快速完成一些可視化的需求。我們可以根據實際情況,調整文字雲的基本參數和美化參數,得到既美觀又有意義的文字雲。在生成文字雲時,我們需要注意去除特殊符號和數字,保證展示的詞彙具備可讀性。同時也可以通過自定義停用詞進行加強。最後,希望這篇關於wordcloud庫的入門指南能夠對你有所幫助。
原創文章,作者:XXOOI,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/375605.html