Deepin上使用Python + word_cloud实现词云

word_cloud安装

word_cloud的Github

wget https://github.com/amueller/word_cloud/archive/master.zip
unzip master.zip
rm master.zip
cd word_cloud-master
python setup.py install

注意(仅供参考,开发环境:deepin15.4+anoconda):安装完后在/home/d4ngy4n/anaconda3/lib/python3.6/site-packages目录下找到wordcloud-1.3.1-py3.6-linux-x86_64.egg文件夹,将文件夹中的wordcloud文件夹剪切复制到/home/d4ngy4n/anaconda3/lib/python3.6/site-packages目录下,将/home/d4ngy4n/anaconda3/lib/python3.6/site-packages/wordcloud-1.3.1-py3.6-linux-x86_64.egg/EGG-INFO目录的所有文件及文件夹剪切复制到/home/d4ngy4n/anaconda3/lib/python3.6/site-packages/wordcloud-1.3.1-py3.6-linux-x86_64.egg目录下.

实现方式

参考10行Python代码的词云

提醒:wordcloud自带的字体库不支持中文,需自己设置fontpath参数更换字体

参考代码

import jieba
f = open('file.txt', 'r', encoding='utf-8').read()
w = open('word_count.txt','w')
#用jieba分词
words = list(jieba.cut(f))
for word in words:
    if len(word) > 1:
        word = word + '\n'
        w.writelines(word)
w.close()

from wordcloud import WordCloud
import PIL
import matplotlib.pyplot as plt
import numpy as np

def wordcloudplot():
    text = open('word_count.txt').read()
    #字体文件的路径(Deepin默认的字体)
    path='/usr/share/fonts/truetype/wqy/wqy-microhei.ttc'
    # 设置词云的样式
    alice_mask = np.array(PIL.Image.open('alice_mask.png'))
    wordcloud = WordCloud(font_path=path,background_color="white", margin=5, width=1800, height=800, mask=alice_mask, max_words=2000,
                          max_font_size=60, random_state=42)
    worcloud = wordcloud.generate(text)
    wordcloud.to_file('word_cloud.jpg')
    plt.imshow(wordcloud)
    plt.axis('off')
    plt.show()

if __name__ == '__main__':
    wordcloudplot()
Deepin上使用Python + word_cloud实现词云_第1张图片
词云样式[alice_mask.png](https://github.com/amueller/word_cloud/blob/master/examples/alice_mask.png)
Deepin上使用Python + word_cloud实现词云_第2张图片
输出结果

出现的问题

  • Fontconfig error: "/home/d4ngy4n/.config/fontconfig/conf.d/99-deepin.conf", line 1: Unsupported version '2.0'

解决办法:删除/home/d4ngy4n/.config/fontconfig/conf.d目录下的99-deepin.conf, 终端下输入
fc-cache -fv

你可能感兴趣的:(Deepin上使用Python + word_cloud实现词云)