我有一些单词和表情符号的句子,我的目标是在其描述中转换表情符号。
示例:“😊你好!”将转换为“ smiling_face_with_smiling_eyes您好!”
实际上,我对编码/解码并不放心,我遇到了一些问题。感谢这里的另一篇文章Converting emojis to unicode and viceversa,我想我可能已经找到了解决方案。不过,我不知道发生了什么以及为什么要这样做。我会感谢一些解释。
我将向您展示两个测试,第一个是失败的测试。你能解释为什么吗?
# -*- coding: UTF-8 -*
unicode = u"\U0001f600"
string = u"\U0001f600 Hello world"
print("SENT: "+string)
输出:已发送:😀Hello world
测试1(失败):
if string.find(unicode):
print("after: "+string.replace(unicode,"grinning_face_with_sweat"))
else:
print("not found : "+unicode)
输出:找不到:😀
测试2:
if string.find(unicode.encode('unicode-escape').decode('ASCII')):
print(string.replace(unicode,"grinning_face_with_sweat"))
else:
print("not found : "+unicode)
输出:grinning_face_with_sweat Hello world
由于unicode
中的文本位于string
的开头,所以string.find(unicode)
返回0。如果未找到,则返回-1。您的代码应为:
if string.find(unicode) != -1:
print("after: "+string.replace(unicode,"grinning_face_with_sweat"))
else:
print("not found : "+unicode)
BTW,您还在使用Python 2吗?我强烈建议您切换到Python3。如果您使用的是Python 3,则无需在字符串前面加上u
,因为Python 3中的所有字符串都是Unicode。