我习惯使用 JSON 和 Numpy 在 python 中存储数组、列表和字典,但我想使用 BSON,因为 float 只占用 4 个字节,从而减少文件大小。
使用 Json,我执行以下操作:
import numpy
import json
a = numpy.random.rand(12).reshape((3,4))
with open('out.json', 'w') as out:
json.dump(a.tolist(), out)
with open('out.json') as inp:
b = numpy.array(json.load(inp))
print b
我没有找到一种明显的方法来对 BSON 执行相同的操作。我试过这个:
import numpy
from bson import BSON
a = numpy.random.rand(12).reshape((3,4))
b = BSON.encode({'a': a.tolist()})
with open('out.bson', 'wb') as out:
out.write(b)
with open('out.bson', 'rb') as inp:
print BSON().decode(inp.read())
但出现此错误:
Traceback (most recent call last):
File "apaga.py", line 12, in <module>
print BSON().decode(inp.read())
File "/usr/lib/python2.7/dist-packages/bson/__init__.py", line 539, in decode
(document, _) = _bson_to_dict(self, as_class, tz_aware)
bson.errors.InvalidBSON: not enough data for a BSON document
最佳答案
我安装的 BSON 版本不会如图所示导入,所以也许我使用的是不同的版本。要在导入后在 python 中查看文档,请输入 help(bson)...
这样的事情应该有效:
import bson
>>> a = numpy.random.rand(12).reshape((3,4))
>>> b = bson.dumps({'a':a.tolist()})
>>> print bson.loads(b)
{u'a': [[0.033390565943162254, 0.7282666963459123, 0.03719924011978737, 0.2664821209717694], [0.6145164300761253, 0.3662769247564551, 0.5973843055182299, 0.42908933503924207], [0.05901830243140804, 0.31533731904861184, 0.7158207045507905, 0.12686922689849378]]}
关于python - 在Python中使用BSON将 float 组序列化/反序列化为二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12272642/