使用 utf-8 字符串解码 msgpack_numpy
Decoding msgpack_numpy with utf-8 strings
我将 python 3.6 与 msgpack==0.5.1
和 msgpack_numpy==0.4.2
一起使用。
当尝试对 dict
进行编码和解码时,要使用 utf-8
处理字符串 以将字典的键恢复为字符串(而不是二进制文件)。
例如:
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'])
但是,当使用 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'}
是否可以使用 msgpack
encode/decode numpy
数组而不将字典的键替换为二进制?
我尝试了不同的打包选项,发现在打包对象时使用 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])
我将 python 3.6 与 msgpack==0.5.1
和 msgpack_numpy==0.4.2
一起使用。
当尝试对 dict
进行编码和解码时,要使用 utf-8
处理字符串
例如:
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'])
但是,当使用 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'}
是否可以使用 msgpack
encode/decode numpy
数组而不将字典的键替换为二进制?
我尝试了不同的打包选项,发现在打包对象时使用 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])