Home > Back-end >  Efficient and pythonic way to search through a long string
Efficient and pythonic way to search through a long string

Time:11-24

I have created some code to search through a string and return True if there is an emoji in the string. The strings are found in a column in a pandas dataframe, and one can assume the string and the length of the dataframe could be arbitrarily long. I then create a new column in my dataframe with these boolean results.

Here is my code:

import emoji

contains_emoji = []
            
for row in df['post_text']:
    emoji_found = False
    for char in row:
        if emoji.is_emoji(char):
            emoji_found = True
            break
    contains_emoji.append(emoji_found)

df['has_emoji'] = contains_emoji

In an effort to get slicker, I was wondering if anyone could recommend a faster, shorter, or more pythonic way of searching like this?

CodePudding user response:

Use emoji.emoji_count():

import emoji

# Create example dataframe
df = pd.DataFrame({'post_text':['           
  • Related