import jieba
from wordcloud import WordCloud
import numpy as np
from PIL import Image
from matplotlib import colors
# 读取全部词语
f = open(r'try1.txt', "r", encoding="utf-8") # 设置文件对象
text = f.read() # 将txt文件的所有内容读入到字符串str中
f.close()
words_list_jieba = jieba.lcut(text)
def findifhave(demo, stop):
for ret in stop:
if (demo == ret):
return 'T'
# 读取停用词
stop = ['\n','\t',' '] # stop=['\n','我'] 如想过滤‘我’字: ①过滤的方法一:加了一个过滤词‘我’;也可过滤多个词,如:stop = ['\n','\t','肺炎']
with open("stop words (+).txt", 'r', encoding='utf-8') as f1: # ②过滤的方法二:在‘stop words’里加一个‘我’字;若想删第二个,换行写下一个词
for line in f1:
stop.append(line.replace("\n", ""))
f1.close()
dict = {} # 这里建一个列表用于记录表中的所有唯一值出现的次数
for key in words_list_jieba:
dict[key] = dict.get(key, 0) + 1
for demo in list(dict.keys()):
if ('T' == findifhave(demo, stop)):
del dict[demo]
# 字典排序
dict1 = sorted(dict.items(), key=lambda d: d[1], reverse=True)
print(dict1)
background_image = np.array(Image.open('china.png'))
colormaps = colors.ListedColormap(['#871A84', '#BC0F6A', '#BC0F60', '#CC5F6A', '#AC1F4A'])
wordcloud = WordCloud(font_path='simhei.ttf', # 字体
prefer_horizontal=0.99,
background_color='white', # 背景色
max_words=200, # 显示单词数 如只出现前20个
max_font_size=100, # 最大字号
stopwords=stop, # 过滤噪声词
mask=background_image, # 背景轮廓
colormap=colormaps, # 使用自定义颜色
collocations=False
).fit_words(dict)
image = wordcloud.to_image()
image.show() # 展示图片
wordcloud.to_file('词云图-9.5(停用词、字数).png') # 保存图片
分词、词云图
于 2023-04-11 14:05:47 首次发布