画个词云吧

import re
import pandas as pd
from scipy.misc import imread  
from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator
import matplotlib.pyplot as plt
import pkuseg

def wordCount(segment_list):
    word_dict = {}
    for item2 in segment_list:
        if item2 not in word_dict:
            word_dict[item2] = 1
        else:
            word_dict[item2] += 1
    return word_dict




f = open(r"停用词2.txt",encoding='utf-8')
stopword_list = [line.strip() for line in f.readlines()]

path_txt = r'C:\Users\14167\Desktop\pbl\刘慈欣-三体.txt'
f2 = open(path_txt, 'r', encoding='UTF-8').read()


seg=pkuseg.pkuseg()

new = re.sub(r'[^\u4e00-\u9fa5]', '', f2)  #去标点 https://github.com/fxsjy/jieba/issues/528

word_list = [word for word in seg.cut(''.join(new)) if word not in stopword_list]

back_color = imread(r"santi.jpg")  # 解析该图片
wc = WordCloud(background_color='black',  # 背景颜色
               max_words=2000,  # 最大词数
               mask=back_color,  # 以该参数值作图绘制词云,这个参数不为空时,width和height会被忽略
               collocations=False,
               #max_font_size=100,  # 字体最大值
               #min_font_size=20,  # 字体最小值
               font_path="C:/Windows/Fonts/SIMYOU.ttf",  # 解决显示口字型乱码问题,可进入C:/Windows/Fonts/目录更换字体
               # random_state=42,  # 为每个词返回一个PIL颜色
               )
wc.generate_from_text(" ".join(word_list))#根据文本绘制云图
# wc.generate_from_frequencies(wordCount(word_list)) #使用频率绘制云图
print(wordCount(word_list))#得到分词各个词频
# 基于彩色图像生成相应彩色
image_colors = ImageColorGenerator(back_color)
# 显示图片
#plt.imshow(wc)
# 关闭坐标轴
#plt.axis('off')
# 绘制词云
plt.figure()

# plt.imshow(wc, interpolation="bilinear")
plt.imshow(wc.recolor(color_func=image_colors))
plt.axis('off')
# 保存图片
#wc.to_file(r'img.jpg')

这是背景得图片,经过ps一波操作提取出来得形状比较好看的
在这里插入图片描述
最后的词云图做出来是这个样子,我试了几个背景颜色,还是黑色好。
看到“程心”这么大个字我就放心了
在这里插入图片描述

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值