gpt4 book ai didi

python - 仅用于表情符号的词云

转载 作者:行者123 更新时间:2023-12-04 03:38:35 24 4
gpt4 key购买 nike

我有一个充满表情符号的文本。

import matplotlib.pyplot as plt
from wordcloud import WordCloud
wordcloud = WordCloud().generate(text)
plt.imshow(wordcloud)
plt.axis("off")
plt.show()
当我尝试为像上面的代码那样的表情符号获取 wordcloud 时,它返回如下错误:
ValueError: We need at least 1 word to plot a word cloud, got 0.
我认为 wordcloud 库无法读取表情符号。
我想得到这样的输出(当然还有表情符号):
wordcloud
有谁知道如何解决这个问题?

最佳答案

如果要创建表情符号词云,首先要获得支持表情符号的字体,例如Symbola并放置 otfttf工作目录中的文件。
然后你需要安装所需的库:

pip install emojis matplotlib wordcloud
之后,您可以使用此代码创建包含表情符号的 Wordcloud。
from wordcloud import WordCloud
from collections import Counter
import matplotlib.pyplot as plt
import emojis

class EmojiCloud:
def __init__(self, font_path='Symbola.otf'):
self.font_path = font_path
self.word_cloud = self.initialize_wordcloud()
self.emoji_probability = None


def initialize_wordcloud(self):
return WordCloud(font_path=self.font_path,
width=2000,
height=1000,
background_color='white',
random_state=42,
collocations=False)


def color_func(self, word, font_size, position, orientation, random_state=None,
**kwargs):
hue_saturation = '42, 88%'

current_emoji_probability = self.emoji_probability[word]
if current_emoji_probability >= 0.10:
opacity = 50
else:
opacity = 75 - current_emoji_probability/0.2 * 5
return f"hsl({hue_saturation},{opacity}%)"

def generate(self, text):
emoji_frequencies = Counter(emojis.iter(text))
total_count = sum(emoji_frequencies.values())

self.emoji_probability = {emoji: count/total_count for emoji, count in emoji_frequencies.items()}
wc = self.word_cloud.generate_from_frequencies(emoji_frequencies)

plt.figure(figsize=(20,10))
plt.imshow(wc.recolor(color_func=self.color_func, random_state=42))
plt.axis("off")
此代码可以按如下方式使用:
text = 'a lot of emojis 😂😂😂😂🤯🤯🤯🚀🚀🚀🍷🍷🍷🍷🍷💡💡😅'

emoji_cloud = EmojiCloud(font_path='./Symbola.otf')
emoji_cloud.generate(text)
这将绘制以下结果:
enter image description here

关于python - 仅用于表情符号的词云,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66473771/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com