Wordcloud for only emojis

Viewed 1273

I have a text full of emojis.

import matplotlib.pyplot as plt
from wordcloud import WordCloud
wordcloud = WordCloud().generate(text)
plt.imshow(wordcloud)
plt.axis("off")
plt.show()

when i try to get a wordcloud for those emojis like the code above, it returns an error like this:

ValueError: We need at least 1 word to plot a word cloud, got 0.

I think the wordcloud library is unable to read emojis. I want to get an output like this(with emojis of course):

wordcloud

Anyone knows how to solve this problem?

1 Answers

If you want to create a wordcloud of emojis, you first have to get a font that supports emojis such as Symbola and place the otf or ttf file within your working directory.

Then you need to install the required library:

pip install emojis matplotlib wordcloud

After that you can use this code to create a Wordcloud containing emojis.

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")

This code can be used as follow:

text = 'a lot of emojis '

emoji_cloud = EmojiCloud(font_path='./Symbola.otf')
emoji_cloud.generate(text)

This will plot the following result: enter image description here

Related