【问题标题】:how to iterate over UTF-8 in Python?如何在 Python 中迭代 UTF-8?
【发布时间】:2020-09-29 04:53:19
【问题描述】:

如何迭代 utf 8?

import string

for character in string.printable[1:]:
    print (character)

UTF-8 大概也有类似的方法?

【问题讨论】:

  • 请说明您要遍历多字节 UTF-8 编码的字节?另请注意,string.printable 中没有多字节字符。
  • 我当时的想法是以 UTF 8 字符开头,然后递增 char
  • UTF-8 不是字符,它是将Unicode字符转换为字节的特定编码方法。推荐阅读:nedbatchelder.com/text/unipain.html

标签: python encoding utf-8 character-encoding ascii


【解决方案1】:

UTF-8 大概也有类似的方法?

您想知道哪些代码点可以在 ascii 范围之外打印吗?还是您想要可打印字符的 utf8 编码?

获取所有 unicode 的所有可打印代码点:

unicode_max = 0x10ffff
printable_glyphs = [ chr(x) for x in range(0, unicode_max+1) if chr(x).isprintable() ]

如上所述,utf8 是一种编码。那时文本被映射到特定字节,以便其他程序可以共享数据。

内存中的文本不是 utf8。每个字符/字形都有一个代码点。

转换为 utf-8

import unicodedata
monkey = unicodedata.lookup('monkey')

print(f"""
    glyph: {monkey}
    codepoint: Dec: {ord(monkey)}
    codepoint: Hex:  {hex(ord(monkey))}

    utf8: { monkey.encode('utf8', errors='strict') }
    utf16: { monkey.encode('utf16', errors='strict') }
    utf32: { monkey.encode('utf32', errors='strict') }
""")

输出:

glyph: ?
codepoint: Dec: 128018
codepoint: Hex:  0x1f412

 utf8: b'\xf0\x9f\x90\x92'
utf16: b'\xff\xfe=\xd8\x12\xdc'
utf32: b'\xff\xfe\x00\x00\x12\xf4\x01\x00'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-09
    • 2013-06-12
    • 2012-08-19
    • 1970-01-01
    • 2015-09-25
    • 2016-03-13
    • 2023-03-19
    相关资源
    最近更新 更多