【问题标题】:Calculate bytes of the unicode character in python在python中计算unicode字符的字节
【发布时间】:2015-06-03 05:19:51
【问题描述】:

我正在编写一个 Python 脚本来从文件中读取 Unicode 字符并将它们插入到数据库中。我只能插入每个字符串的 30 个字节。 在插入数据库之前如何计算字符串的大小(以字节为单位)?

【问题讨论】:

    标签: python unicode byte


    【解决方案1】:

    如果您需要知道字节数(文件大小),只需致电
    bytes_count = os.path.getsize(filename)


    如果你想知道一个 Unicode 字符可能需要多少字节,那么它取决于字符编码:

    >>> print(u"\N{EURO SIGN}")
    €
    >>> u"\N{EURO SIGN}".encode('utf-8') # 3 bytes
    '\xe2\x82\xac'
    >>> u"\N{EURO SIGN}".encode('cp1252') # 1 byte
    '\x80'
    >>> u"\N{EURO SIGN}".encode('utf-16le') # 2 bytes
    '\xac '
    

    要找出一个文件包含多少个 Unicode 字符,您不需要一次读取内存中的整个文件(如果它是一个大文件):

    with open(filename, encoding=character_encoding) as file:
        unicode_character_count = sum(len(line) for line in file)
    

    如果您使用的是 Python 2,请在顶部添加 from io import open

    同一人类可读文本的确切计数可能取决于 Unicode 规范化(不同的环境可能使用不同的设置):

    >>> import unicodedata
    >>> print(u"\u212b")
    Å
    >>> unicodedata.normalize("NFD", u"\u212b") # 2 Unicode codepoints
    u'A\u030a'
    >>> unicodedata.normalize("NFC", u"\u212b") # 1 Unicode codepoint
    u'\xc5'
    >>> unicodedata.normalize("NFKD", u"\u212b") # 2 Unicode codepoints
    u'A\u030a'
    >>> unicodedata.normalize("NFKC", u"\u212b") # 1 Unicode codepoint
    u'\xc5'
    

    如示例所示,单个字符 (Å) 可以使用多个 Unicode 代码点表示。

    要找出文件中有多少用户感知的字符,您可以使用\X 正则表达式(计数扩展字形簇):

    import regex # $ pip install regex
    
    with open(filename, encoding=character_encoding) as file:
        character_count = sum(len(regex.findall(r'\X', line)) for line in file)
    

    例子:

    >>> import regex
    >>> char = u'A\u030a'
    >>> print(char)
    Å
    >>> len(char)
    2
    >>> regex.findall(r'\X', char)
    ['Å']
    >>> len(regex.findall(r'\X', char))
    1
    

    【讨论】:

      【解决方案2】:

      假设您正在将文件中的 unicode 字符读入名为 byteString 的变量中。然后您可以执行以下操作:

      unicode_string = byteString.decode("utf-8")
      print len(unicode_string)
      

      【讨论】:

      • uniChars 具有误导性(您想在 bytes 对象上调用 .decode();您不应该在 Unicode 文本上调用它)。你可能指的是bytestring
      猜你喜欢
      • 1970-01-01
      • 2012-04-08
      • 1970-01-01
      • 2012-04-21
      • 1970-01-01
      • 2014-10-07
      • 2011-05-13
      • 2015-01-21
      相关资源
      最近更新 更多