Lir*_*aro 3 python encoding numpy utf-8 msgpack
我使用 python 3.6msgpack==0.5.1和msgpack_numpy==0.4.2.
尝试对 a 进行编码和解码时dict,需要使用utf-8将 dict 的键恢复为字符串(而不是二进制文件)字符串。
例如:
import msgpack
d = {'key': None}
binary = msgpack.packb(d)
ret = msgpack.unpackb(binary)
ret.keys()
>>> dict_keys([b'key'])
ret = msgpack.unpackb(binary, encoding='utf-8')
ret.keys()
>>> dict_keys(['key'])
Run Code Online (Sandbox Code Playgroud)
但是,在使用时msgpack_numpy,传递会encoding='utf-8'阻止numpy解码:
import numpy as np
import msgpack_numpy as m
m.patch()
d['key'] = np.arange(5)
binary = msgpack.packb(d)
ret = msgpack.unpackb(binary)
ret.keys()
>>> dict_keys([b'key'])
ret[b'key']
>>> array([0, 1, 2, 3, 4])
ret = msgpack.unpackb(binary, encoding='utf-8')
ret.keys()
>>> dict_keys(['key'])
ret['key']
>>> {'data': '\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00', 'kind': '', 'nd': True, 'shape': [5], 'type': '<i8'}
Run Code Online (Sandbox Code Playgroud)
是否可以在不将 dict 的键替换为二进制的情况下对numpy数组进行编码/解码msgpack?
我摆弄了不同的包装选项,发现use_bin_type=True在包装对象时使用可以解决问题。
import msgpack
import numpy as np
import msgpack_numpy as m
m.patch()
d = {'key': np.arange(5)}
binary = msgpack.packb(d, use_bin_type=True)
ret = msgpack.unpackb(binary, encoding='utf-8')
ret.keys()
>>> dict_keys(['key'])
ret['key']
>>> array([0, 1, 2, 3, 4])
Run Code Online (Sandbox Code Playgroud)