<p>我有一个巨大的字典,其中numpy数组作为值,几乎消耗了所有的RAM。不可能完全腌制或压缩。我已经检查了<a href="https://gist.github.com/davidcrawford/6774493" rel="nofollow noreferrer">solutions</a>的<a href="https://stackoverflow.com/questions/11675381/python-compress-large-files">some</a>以使用<code>zlib</code>进行块读/写,但是当我想从RAM读/写时,它们处理的是文件,<code>StringIO</code>等等。在</p>
<p><a href="https://stackoverflow.com/a/33563348/1692060">Here is the closest example to what I want</a>,但它只有写入部分。我怎样才能在保存后读取对象,因为块是一起写的,而压缩的块当然有不同的长度?在</p>
<pre><code>import zlib
class ZlibWrapper():
# chunksize is used to save memory, otherwise huge object will be copied
def __init__(self, filename, chunksize=268435456): # 256 MB
self.filename = filename
self.chunksize = chunksize
def save(self, data):
"""Saves a compressed object to disk
"""
mdata = memoryview(data)
with open(self.filename, 'wb') as f:
for i in range(0, len(mdata), self.chunksize):
mychunk = zlib.compress(bytes(mdata[i:i+self.chunksize]))
f.write(mychunk)
def load(self):
# ???
return data
</code></pre>
<p>不幸的是,未压缩的对象太大,无法通过网络发送,而将它们压缩到外部会造成额外的复杂性。在</p>
<p>Pickle不幸地开始消耗RAM和系统挂起。在</p>
<p>在与Charles Duffy讨论之后,我尝试序列化(目前不起作用-甚至不压缩字符串):</p>
^{pr2}$