txt文件:
data = [ ]
with open ( 'data/data.txt' , 'r' , encoding= 'utf-8' ) as f:
for line in f: # 读取每行, line是字符串格式
'' 'split():将字符串按空格分成列表' ''
data. append ( line. split ( ) )
print ( data)
'' '将嵌套的列表合并成一个列表' ''
merge= sum ( data, [ ] )
print ( merge)
from wordcloud import WordCloud
from collections import Counter
'' '使用函数Counter,可以迅速获取list中每个元素出现的次数' ''
'' '还会按照次数从大到小排序' ''
freq_pos = Counter ( merge)
print ( freq_pos)
'' '绘制词云' ''
backgroud_Image= plt. imread ( 'data/pl.jpg' )
wordcloud = WordCloud ( font_path= "STZHONGS.ttf" ,
max_words= 50 ,
background_color= 'white' ,
mask= backgroud_Image)
pos_wordcloud = wordcloud. fit_words ( freq_pos)
plt. imshow ( pos_wordcloud)
plt. axis ( 'off' )
plt. show ( )