Python生成词云的实现代码
作者:Blue 时间:2023-09-12 22:42:48
1 概述
利用Python生成简单的词云,需要的工具是cython,wordcloud与anaconda.
2 准备工作
包括安装cython,wordcloud与anaconda.
2.1 安装anaconda
下载官网
选择对应的版本下载即可.
2.2 安装cython
cython是为了安装wordcloud准备的.
pip -m pip install --upgrade cython
2.3 安装wordcloud
安装wordcloud前需要先安装Microsoft Visuall C++ 14.0.
这里下载
安装好了以后重启,输入
python -m easy_install wordcloud
3 使用
3.1 打开Jupyter
打开Jupyter Notebook.
然后会在浏览器打开这个页面,新建一个notebook.
先把需要的库导入:
from wordcloud import WordCloud
import matplotlib.pyplot as plt
3.2 创建文字库
简单的文字库可以直接选择一个txt文件,复杂的话可以选择创建一个excel,导出为csv文件,然后利用pandas库的read_csv()读入文件.这里创建一个txt,空格分隔单词即可.
然后上传到Jupyter中:
3.3 生成词云
首先读入文件:
text = open('1.txt').read()
然后使用WordCloud().generate(text),在里面设置各种属性.
wc=WordCloud(
width=800,
repeat=True,
height=800).generate(text)
这里设置了高度与宽度,允许重复.
plt.imshow(wc,interpolation="bilinear")
plt.axis("off")
plt.show()
显示词云,
interpolation='bilinear'
会使显示平滑更加平滑,axis("off")表示不显示坐标轴.
下面是效果:
3.4 注意事项
如果含有汉字,首先在读取时设置编码:
text = open('1.txt',encoding='utf-8')
然后再生成词云时设置字体:
wc = WordCloud(font_path=r'C:\Windows\Fonts\simfang.ttf')
测试:
text=open('1.txt',encoding='utf-8').read()
wc=WordCloud(
width=1300,
repeat=True,
font_path=r'C:\Windows\Fonts\simfang.ttf',
height=1300).generate(text)
plt.imshow(wc,interpolation="bilinear")
plt.axis("off")
plt.savefig('aaaa.jpg')
来源:https://segmentfault.com/a/1190000021574005
标签:Python,词云
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
教你如何利用python3爬虫爬取漫画岛-非人哉漫画
2021-10-01 23:06:57
![](https://img.aspxhome.com/file/2023/0/75130_0s.jpg)
视觉设计的一致性与用户体验
2010-01-06 13:38:00
![](https://img.aspxhome.com/file/UploadPic/20101/11/same_paper-95s.jpg)
Python3中exp()函数用法分析
2023-06-11 03:17:24
Python配置文件管理之ini和yaml文件读取的实现
2022-01-10 15:33:08
Python3.6简单反射操作示例
2021-05-04 03:32:05
![](https://img.aspxhome.com/file/2023/0/105900_0s.png)
php中替换字符串函数strtr()和str_repalce()的用法与区别
2023-11-17 06:12:53
UE、UI、UCD、Interaction Design、UED、UX、HCI、Usability,IA
2022-09-11 04:22:56
SqlServer2016模糊匹配的三种方式及效率问题简析
2024-01-22 09:45:59
Python3.10.4激活venv环境失败解决方法
2022-11-15 10:39:39
![](https://img.aspxhome.com/file/2023/4/75984_0s.png)
利用CSS改善网站可访问性
2010-10-20 20:12:00
MySQL修改配置,区分大小写
2010-12-03 16:31:00
MySQL中in和exists区别详解
2024-01-19 20:55:10
![](https://img.aspxhome.com/file/2023/7/114957_0s.png)
python 使用get_argument获取url query参数
2023-02-12 03:52:18
matlab和Excel的数据交互操作(非xlsread和xlswrite)
2022-06-16 01:00:42
![](https://img.aspxhome.com/file/2023/4/76894_0s.png)
探讨select in 在postgresql的效率问题
2024-01-20 01:41:41
python中如何使用函数改变list
2022-06-04 13:38:38
python笔记之mean()函数实现求取均值的功能代码
2022-01-12 07:06:47
hive中将string数据转为bigint的操作
2024-01-20 15:37:18
python将二维数组升为一维数组或二维降为一维方法实例
2023-07-25 07:51:59
![](https://img.aspxhome.com/file/2023/3/61713_0s.png)
Go语言ORM框架构造查询条件示例详解
2024-05-05 09:29:30