Python学习记录(一)制作词云
2020-02-03 本文已影响0人
徐曼曼_b287
先参考下面教程,从安装anaconda开始
如何用Python做词云?
安装好之后点这个运行命令行

跟着教程里提供的视频,把项目新建到桌面某个文件夹中

因为要制作词云,需要事先安装词云包,输入命令:
pip install wordcloud
直接装不是很好装,大概是网络问题,重新尝试了好多次,才安装成功,也可以先下载下来再安装
然后,输入命令启动Jupyter页面
jupyter notebook
刚启动时,里面啥也没有(我这里面都是后来添加的~)

接下来就是新建项目写代码了:
# 读取文件,文件路径为“yes-minister.txt”
filename="yes-minister.txt"
mytext=open(filename).read()
# 导入词云包
from wordcloud import WordCloud
wordcloud=WordCloud().generate(mytext)
# 显示图片
%matplotlib inline
import matplotlib.pyplot as plt
plt.imshow(wordcloud,interpolation='bilinear')
# 不显示标尺
plt.axis("off")
一步一步作出我的第一张词云,长这样:

诶?说好的炫酷效果呢?

于是接着查,发现原来WordCloud()函数里面可以传许多参数,我可以给加个背景图
那么什么样的背景图符合标准呢?经过多次尝试发现只要背景色和前景色对比度足够大就行了
比如,这样:

于是调整代码:
from wordcloud import WordCloud
# 用于加载图片
import PIL.Image as image
import numpy as np
# 读取文件,文件路径为“皮卡丘.txt”
filename="皮卡丘.txt"
mytext=open(filename).read()
# 打开图片
mask=np.array(image.open("皮卡丘_meitu_2.jpg"))
# 设置背景图片、颜色、字体
wordcloud=WordCloud(background_color='white',font_path=r'wqy-microhei.ttc',mask=mask).generate(mytext)
# 显示图片1
%matplotlib inline
import matplotlib.pyplot as plt
plt.imshow(wordcloud,interpolation='bilinear')
plt.axis("off")
# 显示图片2
imge=wordcloud.to_image().show()
# 保存图片
wordcloud.to_file("pikaqiu1.png")
效果:

这里我显示的是中文,先在网上下载了一个字体:wqy-microhei.ttc
# 设置字体
font_path=r'wqy-microhei.ttc'
后来我就想做一个关于疫情的词云,百度文档找了一个docx文件下载,加载文件名改一改,发现不行~
只能接着百度,如何加载docx文件 ,发现仍需要装另一个包:pip install python-docx
同样,请在网络环境好的地方安装
from wordcloud import WordCloud
import PIL.Image as image
import numpy as np
# 读取doc文档
import docx
from docx import Document
# 便利赋值
doc=Document("新型冠状病毒肺炎科普.docx")
mytext= ""
for paragraph in doc.paragraphs:
mytext=mytext+paragraph.text
mask=np.array(image.open("口罩2.jpg"))
wc=WordCloud(background_color='white',font_path=r'wqy-microhei.ttc',mask=mask).generate(mytext)
%matplotlib inline
import matplotlib.pyplot as plt
# 显示图片1
plt.imshow(wc,interpolation='bilinear')
plt.axis("off")
# 显示图片2
img=wc.to_image().show()
# 保存图片
wc.to_file("virus1.png")


结束~