Word Cloud
TNFSH Python教材

Table of Contents

Hits

1. 事前準備

執行本範例前,請先把下列檔案放在教材(程式)所在目錄:

2. 產生文字雲

 1: from wordcloud import WordCloud, STOPWORDS
 2: import numpy as np
 3: import matplotlib.pyplot as plt
 4: from PIL import Image
 5: import jieba
 6: import jieba.analyse
 7: from collections import Counter # 次數統計
 8: 
 9: dictfile = "dict.txt.big"  # 字典檔(放在程式所在目錄)
10: stopfile = "stopwords.txt"  # stopwords(放在程式所在目錄)
11: fontpath = "NotoSansTC-Medium.otf"  # 字型檔(放在程式所在目錄)
12: 
13: mdfile = "article.txt"  # 要分析的文章(放在程式所在目錄)
14: 
15: jieba.set_dictionary(dictfile)
16: jieba.analyse.set_stop_words(stopfile)
17: 
18: text = open(mdfile,"r",encoding="utf-8").read()
19: 
20: tags = jieba.analyse.extract_tags(text, topK=50)
21: 
22: seg_list = jieba.lcut(text, cut_all=False)
23: dictionary = Counter(seg_list)
24: 
25: freq = {}
26: for ele in dictionary:
27:     if ele in tags:
28:         freq[ele] = dictionary[ele]
29: print(freq) # 計算出現的次數
30: #wordcloud = WordCloud(width=800, height=400).generate(text)
31: wordcloud = WordCloud(width=1024, height=768, background_color="white", contour_width=3, contour_color='steelblue', font_path= fontpath).generate_from_frequencies(freq)
32: plt.figure()
33: plt.imshow(wordcloud, interpolation="bilinear")
34: plt.axis("off")
35: plt.savefig('wc.png', dpi=600)  # 存到目前目錄

Author: Yung Chin

Created: 2026-09-01 二 20:01

Validate