wordcloud词云库的使用
wordcloud库常规方法
w = wordcloud.WordCloud()
w.generate(txt)
向WordCloud对象w中加载文本txt
>>>w.generate("Python and WordCloud")
w.to_file(filename)
将词云输出为图像文件,.png或.jpg格式
>>>w.to_file("outfile.png")
import wordcloud
c = wordcloud.WordCloud() #步骤1:配置对象参数
c.generate("wordcloudby Python") #步骤2:加载词云文本
c.to_file("pywordcloud.png") #步骤3:输出词云文件
w = wordcloud.WordCloud(<参数>)
width指定词云对象生成图片的宽度,默认400像素 >>>w=wordcloud.WordCloud(width=600)
height指定词云对象生成图片的高度,默认200像素 >>>w=wordcloud.WordCloud(height=400)
min_font_size指定词云中字体的最小字号,默认4号 >>>w=wordcloud.WordCloud(min_font_size=10)
max_font_size指定词云中字体的最大字号,根据高度自动调节 >>>w=wordcloud.WordCloud(max_font_size=20)
font_step指定词云中字体字号的步进间隔,默认为1 >>>w=wordcloud.WordCloud(font_step=2)
font_path指定字体文件的路径,默认None >>>w=wordcloud.WordCloud(font_path="msyh.ttc")
max_words指定词云显示的最大单词数量,默认200 >>>w=wordcloud.WordCloud(max_words=20)
stop_words指定词云的排除词列表,即不显示的单词列表 >>>w=wordcloud.WordCloud(stop_words={"Python"})
mask指定词云形状,默认为长方形,需要引用imread()函数 >>>from scipy.miscimport imread >>>mk=imread("pic.png") >>>w=wordcloud.WordCloud(mask=mk)
background_color指定词云图片的背景颜色,默认为黑色 >>>w=wordcloud.WordCloud(background_color="white")
wordcloud应用实例一
import wordcloud
txt = "life is short, you need python"
w = wordcloud.WordCloud(background_color= "white")
w.generate(txt)
w.to_file("pywcloud.png")
wordcloud应用实例二
import jieba
import wordcloud
txt = "程序设计语言是计算机能够理解和识别用户操作意图的一种交互体系,它按照特定规则组织计算机指令,使计算机能够自动进行各种运算处理。"
w = wordcloud.WordCloud( width=1000,font_path=r'C:\Windows\Fonts\msyh.ttf',height=700)
w.generate(" ".join(jieba.lcut(txt)))
w.to_file("pywcloud.png")
wordcloud应用实例三
#GovRptWordCloudv1.py
import jieba
import wordcloud
f = open("新时代中国特色社会主义.txt", "r", encoding="utf-8")
t = f.read()
f.close()
ls = jieba.lcut(t)
txt = " ".join(ls)
w = wordcloud.WordCloud(width = 1000, height = 700,background_color = "white",font_path=r'C:\Windows\Fonts\msyh.ttf')
w.generate(txt)
w.to_file("grwordcloud.png")
参考:https://jingyan.baidu.com/article/456c463b14808c0a59314454.html

浙公网安备 33010602011771号