python词云生成

本文介绍了一个使用Python生成词云的具体实例。通过jieba分词获取文本关键词,并利用WordCloud库结合图片作为遮罩生成词云图。展示了从读取文本到生成词云的完整过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

# encoding=utf-8
"""词云"""
import jieba.analyse
from PIL import Image, ImageSequence
import numpy as np
import matplotlib.pyplot as plt
from wordcloud import WordCloud, ImageColorGenerator
import os

# lyric = ''
# f = open('./01.txt', 'r','utf-8')
# for i in f:
#     lyric += f.read()

current_dir = os.path.abspath('.')
file_name2 = os.path.join(current_dir, '2.txt')
f2 = open(file_name2, encoding="UTF8")
all=f2.readlines()
lyric = ''
for item in all:
    lyric+=item


result = jieba.analyse.textrank(lyric, topK=50, withWeight=True, allowPOS=('ns', 'n', 'vn', 'v'))
print(result)
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')


# from pytagcloud import create_tag_image, make_tags
# from pytagcloud.lang.counter import get_tag_counts
# import webbrowser
# import collections
#
# YOUR_TEXT = "A tag cloud is a visual representation for text data, typically\
# used to depict keyword metadata on websites, or to visualize free form text."
#
# tags = make_tags(get_tag_counts(YOUR_TEXT), maxsize=80)
#
# create_tag_image(tags, 'cloud_large.png', size=(900, 600), fontname='Lobster')
# #
#
# webbrowser.open('cloud_large.png') # see results

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值