【问题标题】:Getting proper length of emojis获得适当长度的表情符号
【发布时间】: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


【解决方案1】:

阅读sys.maxunicode

一个整数,给出最大 Unicode 代码点的值,即 1114111(十六进制的0x10FFFF)。

在 3.3 版中更改:在 PEP 393 之前,sys.maxunicode 用于 可以是0xFFFF0x10FFFF,具体取决于配置 指定 Unicode 字符是否存储为的选项 UCS-2UCS-4

以下脚本应该在 Python 版本 2 和 3 中都可以使用:

# coding=utf-8

from __future__ import print_function
import sys, platform, unicodedata

print( platform.python_version(), 'maxunicode', hex(sys.maxunicode))
tab = '\t'
unistr = u'\u264a \U0001f601'                          ###   unistr = u'♊ ?'
print ( len(unistr), tab, unistr, tab, repr( unistr))
for char in unistr:
    print (len(char), tab, char, tab, repr(char), tab, 
        unicodedata.category(char), tab, unicodedata.name(char,'private use'))

输出 显示不同sys.maxunicode 属性值的结果。例如,如果sys.maxunicode 结果为0xFFFF,则? 字符(Basic Multilingual Plane 上方的unicode 代码点0x1f601)将转换为相应的surrogate pair(代码点u'\ud83d'u'\ude01'):

PS D:\PShell> [System.Console]::OutputEncoding = [System.Text.Encoding]::UTF8

PS D:\PShell> . py -3 D:\test\Python\Py\42783173.py
3.5.1 maxunicode 0x10ffff
3      ♊ ?   '♊ ?'
1      ♊      '♊'      So      GEMINI
1             ' '      Zs      SPACE
1      ?     '?'      So      GRINNING FACE WITH SMILING EYES

PS D:\PShell> . py -2 D:\test\Python\Py\42783173.py
2.7.12 maxunicode 0xffff
4      ♊ ?   u'\u264a \U0001f601'
1      ♊      u'\u264a'    So      GEMINI
1             u' '         Zs      SPACE
1      ��     u'\ud83d'    Cs      private use
1      ��     u'\ude01'    Cs      private use

注意:以上输出示例取自 Unicode-aware Powershell-ISE console pane

【讨论】:

    猜你喜欢
    • 2017-03-14
    • 2021-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-19
    • 2015-01-16
    • 1970-01-01
    相关资源
    最近更新 更多