词云
作业内容:统计歌曲《云与海》的歌词前8个
代码
import jieba jieba.setLogLevel(jieba.logging.INFO) with open('E:/云与海.txt','rb')as f: txt=f.read() f.close() words=jieba.lcut(txt) counts={} for word in words: if len(word)==1: continue else: counts[word]=counts.get(word,0)+1 items= list(counts.items()) items.sort(key=lambda x:x[1],reverse=True) for i in range(8): word,count=items[i] print('{0:<10}{1:>5}'.format(word,count)) from wordcloud import WordCloud newtxt=[] for i in items: newtxt.append(i[0]) newtxt=' '.join(newtxt) print(newtxt) c=WordCloud(font_path='msyh.ttc',\ background_color='pink',\ font_step=10,\ width=400,\ height=200,\ max_words=8,\ max_font_size=80,\ ).generate(newtxt) c.to_file('云与海的歌词.png')
生成图片

浙公网安备 33010602011771号