Replace emoji with text using dictionary

Viewed 894

I have a dictionary called emoji contains emoji and meaning.

{'': 'excited',  '': 'laugh',  '' : 'cry'}

and i have a string as an input called tweet. I try to translate this tweet "I'm so excitedd " using this function below.

def replace_emoji(tweet):
    return ' '.join(emoji.get(x, x) for x in tweet.split())

But it couldn't work if the emoticons have no space between them like this "". So i get output same as the input. Can someone help me to solve this problem?

2 Answers

Similar to the comments above, the issue is the split doesn't work on empty strings. My suggestion would be to replace the list comprehension with a loop that iterates over every character, adding either that character or the translation of the emoji if it is present in the emoji dict:

def replace_emoji(tweet):
    result = ''
    for char in tweet:
        result += emoji.get(char, char)
    return result

In the style of your solution you can also replace the split with a casting of the string to a list and instead of joining on ' ' you can join on '' to get the tweet re-joined successfully:

def replace_emoji(tweet):
    return ''.join(emoji.get(x, x) for x in list(tweet))

Using split() will be the most Pythonic way of splitting on a string.

It's also useful to remember that if you use split() on a string that does not have a white-space then string will be returned to you in a list.

Example:

>>> "".split()
['']

>>> "  ".split()
['','']

if you use list then there is a problem,Each words converted to characters and emoji with without with-space will remain as it is which is not good.

Code:-

def replace_emoji(tweet):
    return ''.join(emoji.get(x, x) for x in list(tweet))
print(replace_emoji("If you're a programmer and blocks of text are needed  "))

Output:- If you're a programmerlaugh and blocks of text are neededcry excitedexcitedexcited Best Solution:

You could try using this emoji package. It's primarily used to convert escape sequences into unicode emoji, but as a result it contains an up to date list of emojis. Code:-

from emoji import UNICODE_EMOJI

def is_emoji(s):
    return s in UNICODE_EMOJI

emoji={'': 'excited',  '': 'laugh',  '' : 'cry'}
def replace_emoji(tweet):
    result = ' '
    for char in tweet:
        if is_emoji(char):
            result = result + ' ' + emoji.get(char, char)
        else:
            result += emoji.get(char, char)
    return result

print(replace_emoji("If you're a programmer and blocks of text are needed  "))

Output: If you're a programmer laugh and blocks of text are needed cry excited excited excited

Related