为什么以下两种解码方法返回不同的结果?
>>> import codecs
>>>
>>> data = ['', '', 'a', '']
>>> list(codecs.iterdecode(data, 'utf-8'))
[u'a']
>>> [codecs.decode(i, 'utf-8') for i in data]
[u'', u'', u'a', u'']
这是错误还是预期行为?我的Python版本2.7.13。
这个是正常的。iterdecode
接受编码块上的迭代器并返回解码块上的迭代器,但它不保证一对一的对应关系。它所保证的是所有输出块的串联是所有输入块的串联的有效解码。
如果你看一下源代码 https://github.com/python/cpython/blob/2.7/Lib/codecs.py#L1029,您会看到它显式丢弃空输出块:
def iterdecode(iterator, encoding, errors='strict', **kwargs):
"""
Decoding iterator.
Decodes the input strings from the iterator using an IncrementalDecoder.
errors and kwargs are passed through to the IncrementalDecoder
constructor.
"""
decoder = getincrementaldecoder(encoding)(errors, **kwargs)
for input in iterator:
output = decoder.decode(input)
if output:
yield output
output = decoder.decode("", True)
if output:
yield output
请注意原因iterdecode
存在,以及你不直接打电话的原因decode
对所有的块来说,解码过程是有状态的。一个字符的 UTF-8 编码形式可能会被分割成多个块。其他编解码器可能具有非常奇怪的有状态行为,例如可能会反转所有字符的大小写的字节序列,直到您再次看到该字节序列。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)