【发布时间】:2017-03-14 10:15:17
【问题描述】:
我注意到,当您在手机信息中输入表情符号时,有些表情符号需要 1 个字符,有些需要 2 个字符。例如,“♊”需要 1 个字符,但“????”需要 2. 在 python 中,我试图获取表情符号的长度,我得到:
len("♊") # 3
len("????") # 4
len(unicode("♊", "utf-8")) # 1 OH IT WORKS!
len(unicode("????", "utf-8")) # 1 Oh wait, no it doesn't.
有什么想法吗?
此站点在Character.charCount() 行中有表情符号长度:http://www.fileformat.info/info/unicode/char/1F601/index.htm
【问题讨论】:
-
相关:How to work with surrogate pairs in Python?。试试
import unicodedata; unistr = u'♊????'; print unistr, repr( unistr), len(unistr); for char in unistr:print len(char), char, repr(char), unicodedata.category(char), unicodedata.name(char,'private use'); -
感谢您的回复,这是您建议的结果:
\u264a\U0001f601 u'\u264a\U0001f601' 2 1 \u264a u'\u264a' So GEMINI 1 \U0001f601 u'\U0001f601' Cn private use如您所见,它仍然将每个表情符号读取为 1 个字符。我确实找到了堆栈问题,但我仍在尝试使代理工作。 -
在我的终端上,
\U0001f601被转换为for …循环中的代理对♊???? u'\u264a\U0001f601' 3...1 ♊ u'\u264a' So GEMINI...1 � u'\ud83d' Cs private use...1 � u'\ude01' Cs private use(使用 ... 而不是换行符) -
我在 python2.7 和 python3.5 中检查了你的代码,我得到了相同的结果 2 个字符。有趣的是我们有不同的最终结果。
-
这是因为
import sys;print hex(sys.maxunicode)在我的py -2中返回'0xffff',在我的py -3中返回'0x10ffff'。 Python 3 为len('????')(字符本身)返回 1,但 Python 2 返回 2(代理对)。
标签: python-2.7 unicode utf-8