Python3 生成中文词云

2019-08-27  本文已影响0人  tafanfly

前提

Python 生成中文词云主要用到两个依赖库:


简单介绍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

详见 Python3 生成英文词云


生成词云

代码如下, 注意以下几点:

#!/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()
上海堡垒
上一篇 下一篇

猜你喜欢

热点阅读