使用utf-8字符串解码msgpack_numpy

时间:2018-01-25 09:44:52

标签: python numpy encoding utf-8 msgpack

我将python 3.6与msgpack==0.5.1msgpack_numpy==0.4.2一起使用。

尝试对dict进行编码和解码时,使用utf-8处理字符串needs,将字典的密钥恢复为字符串(而不是二进制文件)。< / p>

例如:

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'}

是否可以使用numpymsgpack数组进行编码/解码而无需将dict键替换为二进制?

1 个答案:

答案 0 :(得分:1)

我摆弄了不同的打包选项,发现在打包对象时使用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])
相关问题