提要:
该文章记录用于通过读取txt文件中的内容生成词云
代码:
import os
import jieba
from wordcloud import WordCloud
import imageio
def create():
with open('noun.txt', 'r', encoding='utf-8') as f:
text = f.read()
words = jieba.cut(text)
words = list(words)
mask_path = "n.png"
mask = None
if os.path.exists(mask_path):
mask = imageio.v2.imread(mask_path)
wc = WordCloud(background_color='white', width=1920, height=1040, font_path='msyh.ttc', mask=mask)
wc.generate(' '.join(words))
wc.to_file("noun.png")
if __name__ == '__main__':
create()
说明:
这个生成词云的代码基本上就可以通过这个模板来
with open('noun.txt', 'r', encoding='utf-8') as f:
text = f.read()
noun.txt是你要读取的文件,通过这段代码读取
words = jieba.cut(text)
words = list(words)
这段代码则是通过python的jieba库进行分词操作
mask_path = "n.png"
mask = None
if os.path.exists(mask_path):
mask = imageio.v2.imread(mask_path)
这段代码用于设置词云的背景图,也就是将词云弄成你自己想要的图案,
n.png就是背景图,但是要注意背景图的要是白底的。
如下图:
wc = WordCloud(background_color='white', width=1920, height=1040, font_path='msyh.ttc', mask=mask)
wc.generate(' '.join(words))
wc.to_file("noun.png")
这段代码就是生成词云了,wc.to_file(“noun.png”)这里就是将词云结果保存为名字为noun.png的图片。
运行结果:
完成~
开庭的时候带上你的词云。