Skip to content

Instantly share code, notes, and snippets.

@kirberich
Created May 16, 2017 19:03
Show Gist options
  • Save kirberich/01ffa3251436f9ded26b2365f9252f0d to your computer and use it in GitHub Desktop.
Save kirberich/01ffa3251436f9ded26b2365f9252f0d to your computer and use it in GitHub Desktop.
Check if string is a single emoji
"""Check if a string is a single emoji.
Surely there must be a library that does this already, but I couldn't find one.
If you know one, let me know so I can delete this and never speak of it again.
"""
import emoji
# Some of the more complicated emoji are stored with spaces in the emoji library
FIXED_UNICODE_EMOJI = {
key.replace(' ', ''): value for key, value in emoji.UNICODE_EMOJI.items()
}
def is_single_emoji(s):
if s in FIXED_UNICODE_EMOJI:
return True
was_emoji_char = False
was_zero_width_joiner = False
was_variation = False
for index, char in enumerate(s):
is_emoji_char = char in FIXED_UNICODE_EMOJI
is_zero_width_joiner = char == '\u200D'
is_variation = 0xFe00 <= ord(char) <= 0xFE0F or 0x1f3fb <= ord(char) <= 0x1f3ff
if not any([is_emoji_char, is_zero_width_joiner, is_variation]):
# Only emoji characters, join characters and variations can occur in an emoji
return False
if (is_zero_width_joiner or is_variation) and index == 0:
# First character has to be an emoji
return False
if (
(is_zero_width_joiner or is_variation) and
index > 0 and
not (was_emoji_char or was_variation)
):
# If the current character is a separator/variation, the previous needs to be an emoji
return False
if (is_emoji_char and not is_variation) and index > 0 and not was_zero_width_joiner:
# If the current character is an emoji, the previous one can't be an emoji
return False
was_emoji_char = is_emoji_char
was_zero_width_joiner = is_zero_width_joiner
was_variation = is_variation
return True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment