Search code examples
pythonpython-3.xemoji

Get all emojis in a string


I am trying to create a function such that I pass a full string into it and it finds and returns any emojis present. For instance, if there are 2 emojis, it should return both. How can I do so?

Currently, I can only understand how to check for one particular emoji. This is a function I use to check it:

def check(string):
    if '✅' in string:
        print('found', string)

I want to do this without specifying any emoji and just look for all. I have considered from emoji import UNICODE_EMOJI.

import emoji
import regex

def split_count(text):
    emoji_counter = 0
    data = regex.findall(r'\X', text)
    for word in data:
        if any(char in emoji.UNICODE_EMOJI for char in word):
            emoji_counter += 1
            # Remove from the given text the emojis
            text = text.replace(word, '') 

    words_counter = len(text.split())

    return emoji_counter, words_counter

Although this gives us a count, I am not sure how to modify it to get all emojis.


Solution

  • You can check if the letter is in emoji.UNICODE_EMOJI:

    import emoji
    
    def get_emoji_list(text):
        return [letter for letter in text if letter in emoji.UNICODE_EMOJI]
    
    print(get_emoji_list('✅aze✅'))
    # ['✅', '✅']
    

    If you want a set of unique emoji, change your comprehension in the function to create a set instead of a list:

    import emoji
    
    def get_emoji_set(text):
        return {letter for letter in text if letter in emoji.UNICODE_EMOJI}
    
    print(get_emoji_list('✅aze✅'))
    # {'✅'}