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

arc*_*rty 5 utf-8 utf8-decode python-3.x

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

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

我可以通过滚动我自己的utf-8解码功能来解决这个问题,但我宁愿不重新发明轮子,因为我确信这个功能必须已经在其他地方用来解析utf-8字符串.

Kev*_*vin 2

将流包装在TextIOWrapperwith中encoding='utf8',然后调用.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
Run Code Online (Sandbox Code Playgroud)