Python中的Unicode字符转换为Emoji

3

我在格式化字节顺序标记为Unicode时遇到了一些问题。我的字符表达方式有些奇怪。基本上,在Python中无法打印出一个表情符号,而只是字符串。以下是我的示例。

# these codes are coming from a json file; this a representation of one of the codes.
e = 'U+1F600' # smile grin emoji

# not sure how to clean this, so here's a basic attempt using regex.
b = re.compile(r'U\+', re.DOTALL).sub('\U000', e)

print unicode(b) # output should be '\U0001F600'

由于某种原因,这个不会打印出表情符号。

但是,如果您将相同的字符串作为文字直接输入,并使用 u 标志,一切都可以正常工作。

print u'\U0001F600'

我在这里做错了什么?我以为unicode函数会将我的字符串转换为可用的等效形式,但显然不是这样。

我正在使用Python 2.7。

1个回答

12

我猜您要找的是解码

>>> b = '\U0001F600'
>>> print b.decode('unicode-escape')

或者
>>> print unicode(b, 'unicode-escape')


这个问题与

print unicode(b)

这意味着unicode函数试图将字符串\U0001F600转换为unicode,其结果是\\U0001F600。为了防止这种情况,我们提供当前的编码方式为unicode-escape


搞定了!感谢@nu11p01n73R的帮助。那个不规则的原因是什么?它会以何种方式改变输出? - lindsay
2
@lindsay 我已经加上了一个解释。希望它有所帮助。 - nu11p01n73R
@nu11p01n73R,命令后显示的表情符号的数据类型是什么?b 的数据类型又是什么? - babygame0ver
@AkshayKathpal b 是一个 str 类型。 - nu11p01n73R

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接