从字节流中读取utf-8字符

时间:2015-05-14 19:56:39

标签: python-3.x utf-8 utf8-decode

给定一个字节流(生成器,文件等),如何读取单个utf-8编码字符?

  • 此操作必须使用流中该字符的字节。
  • 此操作不得使用超过第一个字符的流的任何字节。
  • 此操作应在任何Unicode字符上成功。

我可以通过滚动我自己的utf-8解码函数来解决这个问题,但我不想重新发明轮子,因为我确信这个功能必须已经在别处用来解析utf-8字符串。

1 个答案:

答案 0 :(得分:2)

使用encoding='utf8'将流包裹在TextIOWrapper中,然后在其上调用.read(1)

这假设您开始使用BufferedIOBase或与其兼容的鸭子类型(即具有read()方法)。如果您有生成器或迭代器,则可能需要调整接口。

示例:

from io import TextIOWrapper

with open('/path/to/file', 'rb') as f:
  wf = TextIOWrapper(f, 'utf-8')
  wf._CHUNK_SIZE = 1  # Implementation detail, may not work everywhere

  wf.read(1) # gives next utf-8 encoded character
  f.read(1)  # gives next byte
相关问题