arc*_*rty 5 utf-8 utf8-decode python-3.x
给定一个字节流(生成器,文件等),我如何读取单个utf-8编码字符?
我可以通过滚动我自己的utf-8解码功能来解决这个问题,但我宁愿不重新发明轮子,因为我确信这个功能必须已经在其他地方用来解析utf-8字符串.
将流包装在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)
| 归档时间: |
|
| 查看次数: |
372 次 |
| 最近记录: |