前提
Python 生成中文词云主要用到两个依赖库:
- jieba:中文分词工具
- wordcloud:词云生成工具
简单介绍jieba
“结巴”中文分词:做最好的 Python 中文分词组件。
安装: pip install jieba / pip3 install jieba
支持三种分词模式:
-
精确模式
,试图将句子最精确地切开,适合文本分析; -
全模式
,把句子中所有的可以成词的词语都扫描出来, 速度非常快,但是不能解决歧义; -
搜索引擎模式
,在精确模式的基础上,对长词再次切分,提高召回率,适合用于搜索引擎分词。
# encoding=utf-8
import jieba
seg_list = jieba.cut("我来到北京清华大学", cut_all=True)
print("Full Mode: " + "/ ".join(seg_list)) # 全模式
seg_list = jieba.cut("我来到北京清华大学", cut_all=False)
print("Default Mode: " + "/ ".join(seg_list)) # 精确模式
seg_list = jieba.cut("他来到了网易杭研大厦") # 默认是精确模式
print(", ".join(seg_list))
seg_list = jieba.cut_for_search("小明硕士毕业于中国科学院计算所,后在日本京都大学深造") # 搜索引擎模式
print(", ".join(seg_list))
输出为
【全模式】: 我/ 来到/ 北京/ 清华/ 清华大学/ 华大/ 大学
【精确模式】: 我/ 来到/ 北京/ 清华大学
【新词识别】:他, 来到, 了, 网易, 杭研, 大厦 (此处,“杭研”并没有在词典中,但是也被Viterbi算法识别出来了)
【搜索引擎模式】: 小明, 硕士, 毕业, 于, 中国, 科学, 学院, 科学院, 中国科学院, 计算, 计算所, 后, 在, 日本, 京都, 大学, 日本京都大学, 深造
更多的安装及介绍见官网:https://github.com/fxsjy/jieba
简单介绍wordcloud
生成词云
代码如下, 注意以下几点:
- cut_the_words() 是利用jieba分词, 入参是中文文本,
comments.txt
是上海堡垒的一些评论文本 - create_worlds_cloud() 是生成词云函数, wordcloud的
默认字体不支持中文
,可以设置支持中文的字体的路径传给font_path
。字体要么已经存在于环境变量中,要么指定字体文件的绝对路径。中文的字体库:https://github.com/adobe-fonts。
#!/usr/bin/env python
# coding=utf-8
import os
import jieba
import numpy as np
from PIL import Image
from wordcloud import WordCloud, STOPWORDS
CURDIR = os.path.abspath(os.path.dirname(__file__))
TEXT = os.path.join(CURDIR, 'comments.txt')
PICTURE= os.path.join(CURDIR, 'alice.png')
FONT = os.path.join(CURDIR, 'Songti.ttc')
def cut_the_words(test=TEXT):
with open(test, 'r') as rp:
content = rp.read()
words_list = jieba.cut(content, cut_all = True)
return ' '.join(words_list)
def create_worlds_cloud():
background = np.array(Image.open(PICTURE))
stopwords = set(STOPWORDS)
for item in ["上海堡垒", "上海", "堡垒"]:
stopwords.add(item)
words = cut_the_words()
wc = WordCloud(background_color="white",
mask=background,
stopwords=stopwords,
font_path=FONT)
wc.generate(words)
wc.to_file('girl.png')
if __name__ == '__main__':
create_worlds_cloud()

网友评论