Python词云

准备工作:

1.下载Anaconda

2.准备好制作词云的文本

3.安装词云包 pip install coludword

4.安装jieba切词包 pip install jieba


1.引入相关的库包:


[python]  view plain  copy
  1. #coding:utf-8  
  2. import jieba    #分词包  
  3. import numpy    #numpy计算包  
  4. import codecs   #codecs提供的open方法来指定打开的文件的语言编码,它会在读取的时候自动转换为内部unicode   
  5. import pandas    
  6. import matplotlib  
  7. matplotlib.use('TKAgg')  
  8. import matplotlib.pyplot as plt  
  9. from wordcloud import WordCloud#词云包  

2.导入皇帝的新衣文件

[python]  view plain  copy
  1. file=codecs.open(u"1.txt",'r')  
  2. content=file.read()  
  3. file.close()  

3.用jieba进行分词

[python]  view plain  copy
  1. segment=[]  
  2. segs=jieba.cut(content) #切词  
  3. for seg in segs:  
  4.     if len(seg)>1 and seg!='\r\n':  
  5.         segment.append(seg)  

4.去高频语气词

[python]  view plain  copy
  1. words_df=pandas.DataFrame({'segment':segment})  
  2. words_df.head()  
  3. stopwords=pandas.read_csv("not.txt",index_col=False,quoting=3,sep="\t",names=['stopword'],encoding="utf8")#去掉我们不需要的高频语气词等  
  4. words_df=words_df[~words_df.segment.isin(stopwords.stopword)]  

5.统计词频

[python]  view plain  copy
  1. words_stat=words_df.groupby(by=['segment'])['segment'].agg({"计数":numpy.size})  
  2. words_stat=words_stat.reset_index().sort_values(by="计数",ascending=False)  

6.使用词云包制作词云

[python]  view plain  copy
  1. from scipy.misc import imread  
  2. import matplotlib.pyplot as plt  
  3. from wordcloud import WordCloud,ImageColorGenerator  
  4. %matplotlib inline  
  5. bimg=imread('timg.jpeg')  
  6. wordcloud=WordCloud(background_color="white",mask=bimg,font_path='simhei.ttf')  
  7. #wordcloud=wordcloud.fit_words(words_stat.head(4000).itertuples(index=False))  
  8. words = words_stat.set_index("segment").to_dict()  
  9. wordcloud=wordcloud.fit_words(words["计数"])  
  10. bimgColors=ImageColorGenerator(bimg)  
  11. plt.axis("off")  
  12. plt.imshow(wordcloud.recolor(color_func=bimgColors))  
  13. plt.show()  

效果如下图:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值