import pandas as pd
import jieba
import matplotlib.pyplot as plt
from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator
# 加載自定義的詞典
jieba.load_userdict('userdict.txt')
jieba.add_word('韓雪')
pd.set_option('display.max_columns', None) # pandas對象顯示所有列,而不是用省略号表示
data = pd.read_csv('actor_danmu.csv', header=None, names=['id', '點贊數', 'Comment'])
comment = ''.join(list(data['Comment'])) # 将清單中的所有字元串拼接在一起
comment_after_split = jieba.cut(str(comment), cut_all=False)
wl_space_split = " ".join(comment_after_split)
# 導入背景圖
backgroud_Image = plt.imread(r'yanyuan.jpg')
stopwords = STOPWORDS.copy()
# 可以加多個屏蔽詞,避免無用的詞出現在詞雲圖中
stopwords.add("感覺")
stopwords.add("這個")
stopwords.add("你們")
stopwords.add("沒有")
stopwords.add("怎麼")
stopwords.add("就是")
stopwords.add("一個")
stopwords.add("為什麼")
stopwords.add("知道")
stopwords.add("真的")
stopwords.add("還是")
stopwords.add("不是")
stopwords.add("覺得")
stopwords.add("什麼")
# 設定詞雲參數
# 參數分别是指定字型、背景顔色、最大的詞的大小、使用給定圖作為背景形狀
wc = WordCloud(
width=1024,
height=768,
background_color='white',
mask=backgroud_Image,
font_path='C:\Windows\Fonts\STZHONGS.TTF',
stopwords=stopwords,
max_font_size=200,
collocations=False, # 避免多個詞重複出現
random_state=50)
wc.generate_from_text(wl_space_split)
img_colors = ImageColorGenerator(backgroud_Image)
wc.recolor(color_func=img_colors)
plt.imshow(wc)
plt.axis('off') # 不顯示坐标軸
plt.show()
# 儲存結果到本地
wc.to_file(r'woshiyanyuan1.jpg')