当我在使用表情符号并试图获取它们的代码点和unicodedata模块的名称时,我一直对多字符表情符号有问题。模块拒绝让我使用字符串,而是使用想要的字符。我尝试了规范化,我尝试了用utf-8和unicode-escape编码,我一遍又一遍地研究它,但是我没有成功地找到正在发生的事情!
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))虽然是的,上面的代码并不使用unicodedata模块,但它向您展示了我有什么问题,不管.
(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在休息之后,我无意间把表情符号从这个:❣️转换成了这个:❣。Python能够很好地处理这个新的表情符号字符。unicodedata模块也喜欢它!
那有什么区别?为什么在我的浏览器和IDE中一个有颜色,而另一个没有?最重要的是,如何在Python中将多字符表情转换为单字符表情符号?
发布于 2022-04-02 00:22:58
一些人类感知的单字符表情符号(称为图形符号)是由多个代码点组成的.这是一个处理它们的方法。我添加了一个复杂的例子:
import unicodedata as ud
emojis = ["", "", "", "", "❣️", "✨", ""]
for emoji in emojis:
print('Emoji:',emoji)
for cp in emoji:
print(f' {cp} U+{ord(cp):04X} {ud.name(cp)}')输出:
Emoji:
U+1F496 SPARKLING HEART
Emoji:
U+1F498 HEART WITH ARROW
Emoji:
U+1F49D HEART WITH RIBBON
Emoji:
U+1F49E REVOLVING HEARTS
Emoji: ❣️
❣ U+2763 HEAVY HEART EXCLAMATION MARK ORNAMENT
️ U+FE0F VARIATION SELECTOR-16
Emoji: ✨
✨ U+2728 SPARKLES
Emoji:
U+1F468 MAN
U+200D ZERO WIDTH JOINER
U+1F469 WOMAN
U+200D ZERO WIDTH JOINER
U+1F467 GIRL
U+200D ZERO WIDTH JOINER
U+1F466 BOY如果表情符号是在一个字符串中,那么处理单个字素的规则是复杂的,而是由第三方regex模块实现的。\X与图形素匹配:
import unicodedata as ud
import regex
for m in regex.finditer(r'\X', '❣️✨'):
emoji = m.group(0)
print(f'{emoji} {ascii(emoji)}')输出:
'\U0001f496'
'\U0001f498'
'\U0001f49d'
'\U0001f49e'
❣️ '\u2763\ufe0f'
✨ '\u2728'
'\U0001f468\u200d\U0001f469\u200d\U0001f467\u200d\U0001f466'https://stackoverflow.com/questions/71713751
复制相似问题