Python画文字云图
- 利用Python画文字云图,必须安装两个包:分词工具包jieba、文字云包wordcloud
- 除了Python之外,R也可以用来做文字云:分词工具包Rwordseg、文字云包wordcloud2
本文主要介绍用Python做文字云图,选取文本《明朝那些事儿 —— 万历十五年的谜团》一章。分词
jieba分词主要有三种模式: - 精确模式,试图将句子最精确地切开,适合文本分析
- 全模式,把句子中所有的可以成词的词语都扫描出来, 速度非常快,但是不能解决歧义
- 搜索引擎模式,在精确模式的基础上,对长词再次切分,提高召回率,适合用于搜索引擎分词
1 | import jieba |
1 | import matplotlib.pyplot as plt |
1 | #导入数据 |
导入的文本中有一些譬如语气词等,对整体的文字云没有帮助,因此需要去掉:1
2
3
4
5
6
7
8
9
10
11
12#去掉一些词语
def seg_sentence(sentence):
sentence_seged = jieba.cut(sentence.strip()) #去除首尾空格
stopwords = open('C:/Users/stop_word.txt').read() #一些语气助词等
outstr = ''
for word in sentence_seged:
if word not in stopwords:
if word != '\t':
outstr += word
outstr += " "
return outstr
data_txt = seg_sentence(data_txt)
1 | #分词 |
画图
词库搜索: https://pinyin.sogou.com/dict/
选择图片如下:(背景白色、形状容易识别的图片效果会更好)1
2
3
4
5
6
7
8
9
10
11#画图准备
cloud_mask=imread(r'D:/ming.jpg')
wordcloud=WordCloud(font_path="D:/simhei.ttf",
mask=cloud_mask,
#stopwords=stopwords,
background_color="white",
max_words=500,
width=1000,
height=860) #,scale=10
words=words_stat.set_index('segment').to_dict()
wordcloud.fit_words(words['计数'])
1 | #绘图 |
最后的成果:
在线工具推荐
大千世界,很多事情都能找到巨人的肩膀来借力,文字云的在线工具就是这个伟大的巨人肩膀,推荐两个:
- 易词云[http://yciyun.com/]
- Tagxedo[http://www.tagxedo.com/app.html]