wordcloud词云--可视化

 1 import jieba
 2 import wordcloud
 3 
 4 f = open("新时代中国特色社会主义.txt", "r", encoding="gbk") #只读.txt文件。这里一定注意是gbk!!!,而不是utf-8(如果出错,请把encoding删除)
 5 
 6 t = f.read()
 7 f.close()
 8 ls = jieba.lcut(t)
 9 
10 txt = " ".join(ls)
11 w = wordcloud.WordCloud(
12     width=1000, height=700,
13     background_color="white",
14     font_path="MSYH.ttc" #没有设置字体可能出现,词云的结果均为方框。建议设置MSYH.ttc/MSYH.TTC(微软雅黑)
15 )
16 w.generate(txt)
17 w.to_file("wordcloud1.png") #在程序当前目录,生成图片wordcloud1.png

 1 import jieba
 2 import wordcloud
 3 from scipy.misc import imread
 4 
 5 mask = imread("chinamap.jpg") #设置背景图片chinamap.jpg
 6 excludes = { }
 7 
 8 f = open("新时代中国特色社会主义.txt", "r", encoding="gbk") #只读.txt文件。这里一定注意是gbk!!!,而不是utf-8(如果出错,请把encoding删除)
 9 
10 t = f.read()
11 f.close()
12 ls = jieba.lcut(t)
13 txt = " ".join(ls)
14 
15 w = wordcloud.WordCloud(
16     width = 550, height = 500,
17     background_color = "white",
18     font_path = "MSYH.ttc", mask = mask #没有设置字体可能出现,词云的结果均为方框。建议设置MSYH.ttc/MSYH.TTC(微软雅黑)
19     )
20 
21 w.generate(txt)
22 w.to_file("wordcloud2.png") #在程序当前目录,生成图片wordcloud2.png

posted @ 2018-07-10 21:29  杨国峰  阅读(3523)  评论(2编辑  收藏  举报