开发手册 欢迎您!
软件开发者资料库

Python wordcloud(词云)安装配置及使用示例代码

本文主要介绍Python中,wordcloud(词云)使用pip安装配置,以及使用的相关示例代码。

1、安装wordcloud(词云)

wordcloud(词云)代码是在Python 2.7、3.4、3.5、3.6和3.7下测试的。wordcloud(词云)依赖numpypillow。安装可以使用pipconda安装,例如,

1)使用pip安装

pip install wordcloud

2)使用conda安装

conda install -c conda-forge wordcloud

安装说明:

要将wordcloud保存到一个文件中,还可以安装matplotlib

如果python版本没有wheels可用,安装包需要设置一个C编译器。在安装编译器之前,报告描述所使用的python和操作系统版本的问题。

2、使用.whl文件安装

除了通过上面命令安装,还可以先下载.whl文件,然后通过文件安装。

下载地址:https://www.lfd.uci.edu/~gohlke/pythonlibs/#wordcloud

从上面地址下载wrapt-1.10.11-cp36-cp36m-win_amd64.whlwordcloud-1.3.2-cp36-cp36m-win_amd64.whl两个文件,具体可以根据需要选择对应版本的这两个文件。然后安装。

pip install wrapt-1.10.11-cp36-cp36m-win_amd64.whl
pip install wordcloud-1.3.2-cp36-cp36m-win_amd64.whl

注意:.whl安装可以拷贝到Python安装目录下的Scripts目录中,然后cdScripts目录。然后在执行上面命令。

3、使用示例代码

#!/usr/bin/env python"""Minimal Example===============Generating a square wordcloud from the US constitution using default arguments."""import osfrom os import pathfrom wordcloud import WordCloud# get data directory (using getcwd() is needed to support running example in generated IPython notebook)d = path.dirname(__file__) if "__file__" in locals() else os.getcwd()# Read the whole text.text = open(path.join(d, 'constitution.txt')).read()# Generate a word cloud imagewordcloud = WordCloud().generate(text)# Display the generated image:# the matplotlib way:import matplotlib.pyplot as pltplt.imshow(wordcloud, interpolation='bilinear')plt.axis("off")# lower max_font_sizewordcloud = WordCloud(max_font_size=40).generate(text)plt.figure()plt.imshow(wordcloud, interpolation="bilinear")plt.axis("off")plt.show()# The pil way (if you don't have matplotlib)# image = wordcloud.to_image()# image.show()

或者

import pandas as pdimport numpy as npimport osfrom wordcloud import WordCloud,ImageColorGeneratorimport matplotlib.pyplot as pltplt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签plt.rcParams['axes.unicode_minus']=False #用来正常显示负号path=os.getcwd()+'\\'+'wonhero.txt'Red_df=pd.read_json(path)print(Red_df["cutword"].sample(4))words=np.concatenate(Red_df.cutword)word_df=pd.DataFrame({"Word":words})word_stat=word_df.groupby(by=["Word"])["Word"].agg({"number":np.size})word_stat=word_stat.reset_index().sort_values(by="number",ascending=False)print(word_stat.head(5))worddict={}for key,value in zip(word_stat.Word,word_stat.number): worddict[key]=value#生成词云redcold=WordCloud(font_path="/Library/Fonts/Hiragino Sans GB W3.ttc", margin=5,width=1800,height=1000, max_words=500,min_font_size=5, background_color='white', max_font_size=250,)redcold.generate_from_frequencies(frequencies=worddict)plt.figure(figsize=(8,8))plt.imshow(redcold)plt.axis('off')plt.show()

httpswwwwonherocom

官方地址https://github.com/amueller/word_cloud