最近学习了Python的语法,写了个生成云图的小demo .
代码在Jupyter Notebook上运行
安装执行python -m pip install –upgrade pip
python -m pip install jupyter
首先读取文本
filename = "E:\codeStyle.txt"
with open(filename,encoding='utf-8') as f:
mytext = f.read()
通过jieba分词
import jieba
mytext = "".join(jieba.cut(mytext))
接下来就是用wordcloud生成云图了
from wordcloud import WordCloud
import imageio
from os import path
#path.join(path.dirname(__file__),"timg.jpg")
trump_coloring = imageio.imread(path.join(path.abspath('.'),"E:\\timg.jpg"))
wordcloud = WordCloud(font_path="E:\\simsun.ttf",
margin=5,
width=1800,
height=800,
background_color="white",
max_words=300,
mask=trump_coloring,
max_font_size=40,
random_state=42).generate(mytext)
import matplotlib.pyplot as plt
#%pylab inline 这行会报提示"Populating the interactive namespace from numpy and matplotlib"
plt.imshow(wordcloud, interpolation='bilinear')
wordcloud.to_file('E:\\output.png')
plt.axis("off")
plt.show()
这里面有几个坑
1:必须是实际存在的.py文件,如果在命令行执行,则会引发异常NameError: name file is not defined;应该结合os.path.abspath()使用
2:如果报类似”ImportError: No module named scipy.misc”这样的异常,就用pip安装对应的组件
3.默认字体不支持中文,我们需要自己下载字体放到当前目录