Compare emoticons and put spaces around them in python

Viewed 1452

I have a dataset and ,when I am encountering an emoticons without any space , I want to place space around them but I don't know few things

  • I have this list

    sentences=["HiRob","swiggy",""].
    

    how to compare them as they are stored as strings.

  • How to put spaces around them?

    Desired output

    sentences=["HiRob  ","swiggy","   "]
    

My basic problem is to put spaces around them.

1 Answers

You can use the emoji package to simplify a bit your code.

from emoji import UNICODE_EMOJI

# search your emoji
def is_emoji(s, language="en"):
    return s in UNICODE_EMOJI[language]

# add space near your emoji
def add_space(text):
    return ''.join(' ' + char if is_emoji(char) else char for char in text).strip()

sentences=["HiRob","swiggy",""]
results=[add_space(text) for text in sentences]

print(results)

output

['HiRob ', 'swiggy', ' ']

Try it online!

related to: How to extract all the emojis from text?

if add_space looks like black magic, here is a friendlier alternative:

def add_space(text):
  result = ''
  for char in text:
    if is_emoji(char):
      result += ' '
    result += char
  return result.strip()
Related