import jieba
import pandas as pd
import numpy as np
import PIL.Image as Image
from wordcloud import WordCloud
#读取stopwords.txt
with open('stopwords.txt','r',encoding ='utf-8') as f:
st = f.readlines()
stopwords = [i.strip() for i in st]
with open('中国共产主义青年团第十九次全国代表大会报告.txt','r') as f:
d = f.read()
words = [i.strip().replace('\n','') for i in jieba.lcut(d)]
#去除停用词
for j in stopwords:
if j in words:
#将words中的每一个j都删除
for k in range(words.count(j)):
words.remove(j)
#统计词频并降序排列value_counts(values,sort=True,ascending=False,normalize=False,bins=None,dropna=True)
dicts = pd.value_counts(words)
#如果只有一个字符去掉
drop_index = []
for i in dicts.index:
if len(i) == 1:
drop_index.append(i)
dict_sort_notone = dicts.drop(drop_index)
#取前100条数据
top_100 = dict_sort_notone[:100]
sd = [i for i in top_100.index]
res = ' '.join(sd)
pic = np.array(Image.open("pic.jpg"))
wordclo = WordCloud(
font_path='HGBS1_CNKI.TTF', # 设置字体,本机的字体
mask=pic, # 设置背景图片
background_color='white', # 设置背景颜色
max_font_size=180, # 字体最大值
max_words=1000, # 设置最多字数
stopwords={'呢'} # 设置停用词,不出现
).generate(res)
"""
整体是根据排序进行绘制大小
就是res字符中谁靠前,谁绘制的越大
"""
image = wordclo.to_image()
image.show() #显示图片
wordclo.to_file('result.png')