【问题标题】:Decoding msgpack_numpy with utf-8 strings使用 utf-8 字符串解码 msgpack_numpy
【发布时间】:2018-01-25 09:44:51
【问题描述】:

我使用带有msgpack==0.5.1msgpack_numpy==0.4.2 的python 3.6。

当尝试对dict 进行编码和解码时,要使用utf-8 处理字符串needs 以将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'])

但是,当使用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 编码/解码numpy 数组而不用将字典的键替换为二进制?

【问题讨论】:

    标签: python numpy encoding utf-8 msgpack


    【解决方案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])
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-09
    • 2018-06-29
    • 2022-11-12
    • 1970-01-01
    • 1970-01-01
    • 2012-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多