演示:
不羅嗦,直接先上代碼。
from wordcloud import WordCloud
import jieba
from matplotlib import pyplot as plt
from PIL import Image
import numpy as np
path = r'E:\123\教程' #文本路徑
path_ph = r'E:\123\教程' #詞雲背景模板路徑
font = r'C:\Windows\Fonts\FZSTK.TTF' #設置字體,可以顯示中文。
text = (open(path + r'\job.txt', 'r', encoding='utf-8')).read() # gbk <--> utf-8
cut = jieba.cut(text) # 使用 jieba庫 分詞
string = ' '.join(cut)
print(len(string)) # 輸出詞量
img = Image.open(path_ph + r'\2.jpg') # 打開圖片
img_array = np.array(img) # 將圖片裝換爲數組
stopword = ['Unword'] # 設置停止詞,也就是你不想顯示的詞,可有可無,看情況處理
wc = WordCloud(
background_color='white', #設置顯示內容在什麼顏色內
width=1000, #設置圖片寬
height=800, #設置圖片高
mask=img_array, #設置詞雲背景模板
font_path=font, #設置字體路徑
stopwords=stopword,
scale=10 #圖像清晰度,數值越大越清晰,最好在10-30之間。
)
wc.generate_from_text(string) # 繪製圖片
plt.imshow(wc)
plt.axis('off') #關閉座標軸
plt.show() # 顯示圖片
wc.to_file(path + r'\wordcloud1.png') # 保存圖片
使用之前需要將需要的第三方庫先下載安裝完。(wordcloud、jieba、matplotlib、PIL、numpy)
可以通過pip安裝。
如果還不會的可以看我的另一個文章———>pip 安裝,更新,卸載,查看模塊方法
Note:有時候你們生成的詞雲可能不清晰,是因爲沒有設置 scale 值 ,設置完後會讓生成的詞雲圖像變得清晰。