While I was working with emojis and attempting to acquire their codepoint and names with the unicodedata module, I kept having issues with multi-character emojis. The module refuses to let me use strings and instead wanted characters. I tried normalizing, I tried encoding in utf-8 and unicode-escape, and I researched it again and again, but I was not successful in finding what was going on!
emojis = ["", "", "", "", "❣️", "✨"]
for emoji in emojis:
codepoint: str = hex(ord(emoji))
filename = 'emoji_u{0}.png'.format(codepoint[2:])
print('{emoji} ({codepoint}) => {filename}'.format(emoji=emoji,
codepoint=codepoint,
filename=filename))
While yes, the above code does not use the unicodedata module, it shows you what I was having a problem with regardless...
(0x1f496) => emoji_u1f496.png
(0x1f498) => emoji_u1f498.png
(0x1f49d) => emoji_u1f49d.png
(0x1f49e) => emoji_u1f49e.png
Traceback (most recent call last):
File "F:/Programming/Languages/Vue.js/lovely/collect.py", line 8, in <module>
codepoint: str = hex(ord(emoji))
TypeError: ord() expected a character, but string of length 2 found
After a break, somehow, I managed to convert the emoji unintentionally, from this: ❣️ to this: ❣. Python was able to process this new emoji character perfectly fine. The unicodedata module likes it too!
So what's the difference? Why does one have color and not the other in both my browser and IDE? And most importantly, how do I convert multi-character emojis to single-character emojis in Python?
Some human-perceived single-character emoji (called graphemes) are made up of multiple code points. Here's a way to handle them. I added a complicated example:
Output:
If the emoji are in a single string the rules for processing a single grapheme are complicated, but implemented by the 3rd party
regexmodule.\Xmatches graphemes:Output: