时间:2021-07-01 10:21:17 帮助过:81人阅读
今天要生成的是励志歌曲的词云,百度文库里面找了20来首,如《倔强》,海阔天空是,什么的大家熟悉的。
所要用到的python库有 jieba(一个中文分词库)、wordcould 、matplotlib、PIL、numpy。
首先我们要做的是读取歌词。我将歌词存在了文件目录下励志歌曲文本中。
现在来读取他
#encoding=gbklyric= ''f=open('./励志歌曲歌词.txt','r')for i in f: lyric+=f.read()
加入#encoding=gbk是为了防止后面操作报错SyntaxError: Non-UTF-8 code starting with '\xc0'
然后我们用jieba分词来对歌曲做分词提取出词频高的词
import jieba.analyse result=jieba.analyse.textrank(lyric,topK=50,withWeight=True) keywords = dict()for i in result: keywords[i[0]]=i[1]print(keywords)
得到结果:
然后我们就可以通过wrodcloud等库来生成词云了
首先先自己找一张图片来作为生成词云的形状的图
from PIL import Image,ImageSequenceimport numpy as npimport matplotlib.pyplot as pltfrom wordcloud import WordCloud,ImageColorGenerator image= Image.open('./tim.jpg') graph = np.array(image) wc = WordCloud(font_path='./fonts/simhei.ttf',background_color='White',max_words=50,mask=graph) wc.generate_from_frequencies(keywords) image_color = ImageColorGenerator(graph) plt.imshow(wc) plt.imshow(wc.recolor(color_func=image_color)) plt.axis("off") plt.show()
保存生成图片
wc.to_file('dream.png')
完整代码:
#encoding=gbkimport jieba.analysefrom PIL import Image,ImageSequenceimport numpy as npimport matplotlib.pyplot as pltfrom wordcloud import WordCloud,ImageColorGenerator lyric= ''f=open('./励志歌曲歌词.txt','r')for i in f: lyric+=f.read() result=jieba.analyse.textrank(lyric,topK=50,withWeight=True) keywords = dict()for i in result: keywords[i[0]]=i[1]print(keywords) image= Image.open('./tim.jpg') graph = np.array(image) wc = WordCloud(font_path='./fonts/simhei.ttf',background_color='White',max_words=50,mask=graph) wc.generate_from_frequencies(keywords) image_color = ImageColorGenerator(graph) plt.imshow(wc) plt.imshow(wc.recolor(color_func=image_color)) plt.axis("off") plt.show() wc.to_file('dream.png')
以上就是python生成词云方法教程的详细内容,更多请关注Gxl网其它相关文章!