最近學習了Python的語法,寫了個生成雲圖的小demo .python
代碼在Jupyter Notebook上運行
安裝執行python -m pip install –upgrade pip
python -m pip install jupyter dom
首先讀取文本
filename = "E:\codeStyle.txt"
with open(filename,encoding='utf-8') as f:
mytext = f.read()學習
經過jieba分詞
import jieba
mytext = "".join(jieba.cut(mytext))字體
接下來就是用wordcloud生成雲圖了 spa
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.默認字體不支持中文,咱們須要本身下載字體放到當前目錄 code