我有一些带有单词和表情符号的句子,我的目标是在它们的描述中转换表情符号
Example: "😊 Hello!" will converted in "smiling_face_with_smiling_eyes Hello!"
事实上,我对编码/解码并不放心,我遇到了一些问题。多亏了这里的另一篇帖子Converting emojis to unicode and viceversa,我想我可能已经找到了解决办法。尽管如此,我还是不明白这是怎么回事,也不明白我为什么要这么做。我希望你能解释一下
我将向您展示两个测试,第一个是失败的测试。你能解释一下原因吗
# -*- coding: UTF-8 -*
unicode = u"\U0001f600"
string = u"\U0001f600 Hello world"
print("SENT: "+string)
输出:已发送:😀 你好,世界
测试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)
输出:咧嘴笑着,满脸是汗你好世界
由于来自
unicode
的文本位于string
的开头,因此string.find(unicode)
返回0。如果未找到,则返回-1。您的代码应该是:顺便说一句,你还在使用Python2吗?我强烈建议切换到Python 3。如果您使用的是Python3,则不需要在字符串前面加上
u
,因为Python3中的所有字符串都是Unicode相关问题 更多 >
编程相关推荐