根据词频生成词云

#-*- coding: utf-8 -*-
#.py文件名不能和引用的库名重复
"""
Created on Sun Mar  8 11:01:44 2020
@author: toto
"""
 
import os,jieba
 
from wordcloud import WordCloud
from PIL import Image
import numpy as np
 
cwd = os.getcwd()#当前工作路径
 
#os.path.join(cwd,文件名)== 文件名
jieba.load_userdict("UserDict.txt")#加载自定义词典文本
 
book = "Solitude.txt"#处理的书籍文本,注意检查不要乱码
stop_word = "stop_word.txt"#停用词文本
top_word = "TopWord.txt"#高频词文本
 
type_pic = "Marquez.jpeg"#白背景词云掩膜图片
cloud = "Solitudecloud.png"#词云图
 
##——分词——
#读取txt书籍文件
fb = open(book,'r',encoding='UTF-8')
book_txt = fb.read()
 
#读取txt停用词文件
ff = open(stop_word,'r',encoding='UTF-8')
stop_word_txt = ff.read()
 
#拆分词语存入列表
#jieba.add_word("何塞·阿尔卡蒂奥·布恩迪亚")
word_ls = jieba.lcut(book_txt,cut_all=False,HMM=True) # 精确模式
#print(word_ls)
 
##——统计词频——
word_dict = {}
 
for i in word_ls:
    
    if i not in stop_word_txt:
    
        word_dict[i] = word_dict.get(i, 0) + 1
 
#print(word_dict)
 
word_ls = sorted(word_dict.items(), key=lambda x: x[1], reverse=True)#变成以(词语,次数)为元组的列表
print(word_ls[0:101])
 
 
#写入高频词文本
#fw = open(top_word,"wt",encoding="utf-8")
top_word = []
for j in range(200):
    
    top_word.append(word_ls[j][0])
 
top_word_txt = " ".join(top_word)     
    
##——生成词云——
Marquez_mask = np.array(Image.open(type_pic))
wordcloud_Solitude = WordCloud(
        background_color="white", 
        max_words=200,
    	# 添加遮罩层
        mask=Marquez_mask,
        # 生成中文字体
        font_path = os.path.join(cwd,"SIMKAI.TTF"),
        contour_width=3,
        min_font_size=2,
        #max_font_size=40,
        )
 
wordcloud_Solitude.generate(top_word_txt)#注意函数参数是列表,不是txt文本
wordcloud_Solitude.to_file(cloud)
 
 
fb.close()
ff.close()
#拓展——jieba自定义词典正则表达式匹配(如何塞·阿尔卡蒂奥·布恩迪亚)
  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

进击的黑蛋

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值