公号:码农充电站pro
主页:https://codeshellme.github.iohtml
今天来介绍一下如何使用 Python 制做词云。python
词云又叫文字云,它能够统计文本中频率较高的词,并将这些词可视化,让咱们能够直观的了解文本中的重点词汇。git
词的频率越高,词显示的大小也就越大。github
wordcloud 是一个词云生成器,它不只是一个 Python 库,仍是一个命令行工具。咱们能够经过 wordcloud 官方文档,和示例库来学习如何使用它。算法
在使用 wordcloud 以前,须要先安装它:shell
pip install wordcloud
WordCloud 类用于建立词云对象
,先来看下它的原型:app
WordCloud(font_path=None, width=400, height=200, margin=2, ranks_only=None, prefer_horizontal=0.9, mask=None, scale=1, color_func=None, max_words=200, min_font_size=4, stopwords=None, random_state=None, background_color='black', max_font_size=None, font_step=1, mode='RGB', relative_scaling='auto', regexp=None, collocations=True, colormap=None, normalize_plurals=True, contour_width=0, contour_color='black', repeat=False, include_numbers=False, min_word_length=0, collocation_threshold=30)
能够看到,WordCloud 类有不少参数能够设置,这里介绍一些经常使用的参数:dom
.ttf
为后缀。
在建立好词云对象
后,可使用 generate
方法生成词云,并使用 to_file
方法将词云图像保存在文件中。工具
generate
方法的原型以下:学习
generate(text)
参数text
是一个用空格
隔开的文本字符串。若是分析的是中文,须要先用 jieba 进行分词,能够参考这里。
除了将词云图像保存在文件中,还可使用 Matplotlib 模块显示词云图像,示例代码以下:
import matplotlib.pyplot as plt plt.imshow(wordcloud) # wordcloud 是词云对象 plt.axis("off") # 用于关闭坐标轴 plt.show()
下面演示一个最简单的示例,来看如何使用 wordcloud。
首先建立词云对象
:
from wordcloud import WordCloud wc = WordCloud()
生成词云:
text = "Python is a programming language, it is easy to use." wc.generate(text)
词云对象的 words_
属性中存储了每一个单词的(归一化后的)权重,权重的范围是 (0, 1]
。
words_
属性是一个字典类型,它存储的键的最大个数为 max_words
,即 WordCloud
类的参数。
以下:
>>> wc.words_ {'Python': 1.0, 'programming': 1.0, 'language': 1.0, 'easy': 1.0, 'use': 1.0} # 示例中的这些单词出现的频率都相等(均为 1), # 因此它们的权重都是 1。
用 Matplotlib 展现词云图像:
import matplotlib.pyplot as plt plt.imshow(wc) plt.axis("off") plt.show()
词云图像以下:
我在这里准备了一个案例,是对1000 首古诗作词云分析。
代码目录以下:
wordcloud/ ├── SimHei.ttf ├── gushi.txt └── gushi_wordcloud.py
其中:
我将代码也放在这里,方便查看:
#!/usr/bin/env python # coding=utf-8 import os import sys import jieba from wordcloud import WordCloud if sys.version.startswith('2.'): reload(sys) sys.setdefaultencoding('utf-8') # 去掉一些做者的名字 STOPWORDS = [ u'李白', u'杜甫', u'辛弃疾', u'李清照', u'苏轼', u'李商隐', u'王维', u'白居易', u'李煜', u'杜牧', ] def load_file(file_path): if sys.version.startswith('2.'): with open(file_path) as f: lines = f.readlines() else: with open(file_path, encoding='utf-8') as f: lines = f.readlines() content = '' for line in lines: line = line.encode('unicode-escape').decode('unicode-escape') line = line.strip().rstrip('\n') content += line words = jieba.cut(content) l = [] for w in words: # 若是词的长度小于 2,则舍去 if len(w) < 2: continue l.append(w) return ' '.join(l) if __name__ == '__main__': file_path = './gushi.txt' content = load_file(file_path) wc = WordCloud( font_path="./SimHei.ttf", stopwords=STOPWORDS, width=2000, height=1200) wc.generate(content) wc.to_file("wordcloud.jpg")
其中:
STOPWORDS
停用词列表,是一些做者的名字。load_file
方法用于加载文本,其中用到了 jieba 分词。最后将词云图像保存在了 wordcloud.jpg
文件中,以下:
咱们也能够从词云对象的words_
属性中查看每一个词的权重,这里我列出前十个:
('明月', 1.0) ('今日', 0.9130434782608695) ('不知', 0.8405797101449275) ('何处', 0.8260869565217391) ('不见', 0.8115942028985508) ('春风', 0.7536231884057971) ('无人', 0.7536231884057971) ('不可', 0.7536231884057971) ('万里', 0.7536231884057971) ('现代', 0.6666666666666666)
(本节完。)
推荐阅读:
欢迎关注做者公众号,获取更多技术干货。