分词、词云图

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')  # 保存图片

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值