写在开头
最近对词云有些兴趣,就自己瞎琢磨研究一些这方面的知识,期间也遇到一些小问题,写下此篇文章留作备注吧。
研究对象
金庸老先生的《天龙八部》
正式开始(微笑脸)
- 统计字频
(1)先统计下小说的字频数:
天龙八部总共用字量4134个,top20的字不出意外都是一些常用词,不过“一”竟然排名第二很让我意外。
# -*- coding:utf-8 -*-
import re
wordcount = {}
stopwords=[]
# stopwords = [u'好',u'一',u'的',u'了']
with open('F:\\tlbb.txt','r') as files:
text = files.read().decode('gb18030')
text = text.strip('\n').strip('\t').strip(' ')
string = re.sub("[\s+\.\!\/_,$%^*(+\"\']+|[:“”+——!,。?、~@#¥%……&*()]+".decode("utf8"), "".decode("utf8"),text) #去除标点符号
for word in string:
if word in stopwords:
continue
wordcount[word] = wordcount.get(word,0)+1
wordcount = sorted(wordcount.items(),key=lambda d:d[1],reverse=True)
print len(wordcount)
for x in xrange(20):
print wordcount[x][0]+':'+str(wordcount[x][1])
files.close()
*执行结果*
字数: 4134
以下是排名前20的各个子的数量统计
不:20125
一:18732
的:18565
是:16524
道:15564
了:15413
人:12627
我:11000
你:10108
这:9893
他:9794
大:9083
来:8870
之:8064
说:7123
中:7056
得:6651
在:6624
下:6465
上:6443
- 词频统计及词云图制作
从词云图中可以看出三大主角的名字还是很凸显。当然我也看到词云图中的“一个”了,想不到这个词的占比挺高的。
本来是想借助上面统计字频,做一个停用词集的。但是没有弄好,添加到stopwords参数中,完全没有效果,只能回头再研究研究。当然如果读到此处你的知道怎么回事,烦请告知,感激不尽呀!
以下是词云代码:
# -*- coding:utf-8 -*-
#天龙八部分词统计
import jieba
from wordcloud import WordCloud,STOPWORDS
import matplotlib.pyplot as plt
s={}
with open('F:\\tlbb.txt','r') as files:
fid = files.read()
fc = jieba.cut(fid) #用jieba分词
for words in fc:
if len(words)>1:
s[words] = s.get(words,0)+1
word = sorted(s.items(),key=lambda (word,count):count,reverse=True)
word = dict(word[1:100])
# for x in word:
# print x ,
wordcloud = WordCloud(font_path = 'C:/Windows/Fonts/msyh.ttf', # 设置字体格式,如不设置显示不了中文
background_color="black", # 设置背景颜色
stopwords=STOPWORDS, # 设置停用词
max_font_size=40, # 设置字体最大值
random_state=30, # 设置有多少种随机生成状态,即有多少种配色方案
relative_scaling=.5
).fit_words(word) #word为字典格式
plt.figure()
plt.imshow(wordcloud)
plt.axis("off")
plt.show()
files.close()
问题总结
- WordCloud().fit_words(word) 中的这个word是传入的是字典,之前一直传入错误,看了源码才恍然大悟
- 词云图中停用词的添加失败
参考
- Python word_cloud 样例 标签云系列(三)
http://www.cnblogs.com/Yiutto/p/5998417.html - Python之天龙八部词云生成分析
http://blog.csdn.net/u013473520/article/details/51764334
最后希望对看到此处的你有所帮助【微笑】