简单模式
from wordcloud import WordCloud
with open("text.txt" ,encoding="utf-8")as file:
#1.读取文本内容
text=file.read()
#2.设置词云的背景颜色、宽高、字数
wordcloud=WordCloud(font_path="C:/Windows/Fonts/simfang.ttf",background_color="white",width=900,height=600,max_words=30,max_font_size=20).generate(text)
#3.生成图片
image=wordcloud.to_image()
#4.显示图片
image.show()
选取背景图作为
from wordcloud import WordCloud
import jieba
import numpy
import PIL.Image as Image
import matplotlib.colors as colors
#1.将字符串切分
def chinese_jieba(text):
wordlist_jieba=jieba.cut(text)
space_wordlist=",".join(wordlist_jieba)#以逗号为分隔开
return space_wordlist
with open("txt.txt" ,encoding="utf-8")as file:
text=file.read()
text=chinese_jieba(text)
#2.图片遮罩层
mask_pic=numpy.array(Image.open("zan.jpg"))
wordcloud=WordCloud(font_path="C:/Windows/Fonts/simfang.ttf",mask=mask_pic,background_color="cornflowerblue",width=3900,height=3900,max_words=50000).generate(text)
image=wordcloud.to_image()
image.show()
第三种
from wordcloud import WordCloud
import jieba
import numpy
import PIL.Image as Image
#1.将字符串切分
def chinese_jieba(text):
wordlist_jieba=jieba.cut(text)
space_wordlist=",".join(wordlist_jieba)
return space_wordlist
with open("txt.txt" ,encoding="utf-8")as file:
text=file.read()
text=chinese_jieba(text)
#2.图片遮罩层
mask_pic=numpy.array(Image.open("ditu.jpg"))
#3.将参数mask设值为:mask_pic
wordcloud=WordCloud(font_path="C:/Windows/Fonts/simfang.ttf",mask=mask_pic,background_color="white",width=3900,height=3900,max_words=50000).generate(text)
image=wordcloud.to_image()
image.show()