好的,根据 Anthony Scopatz 的方法,我有一个可行的解决方案。
def recordStringInHDF5(h5file, group, nodename, s, complevel=5, complib='zlib'):
'''creates a CArray object in an HDF5 file
that represents a unicode string'''
bytes = np.fromstring(s.encode('utf-8'),np.uint8)
atom = pt.UInt8Atom()
filters = pt.Filters(complevel=complevel, complib=complib)
ca = h5file.create_carray(group, nodename, atom, shape=(len(bytes),),
filters=filters)
ca[:] = bytes
return ca
def retrieveStringFromHDF5(node):
return unicode(node.read().tostring(), 'utf-8')
如果我运行这个:
>>> h5file = pt.openFile("test1.h5",'w')
>>> recordStringInHDF5(h5file, h5file.root, 'mrtamb',
u'\u266b Hey Mr. Tambourine Man \u266b')
/mrtamb (CArray(30,), shuffle, zlib(5)) ''
atom := UInt8Atom(shape=(), dflt=0)
maindim := 0
flavor := 'numpy'
byteorder := 'irrelevant'
chunkshape := (65536,)
>>> h5file.flush()
>>> h5file.close()
>>> h5file = pt.openFile("test1.h5")
>>> print retrieveStringFromHDF5(h5file.root.mrtamb)
♫ Hey Mr. Tambourine Man ♫
我已经能够使用 300kB 范围内的字符串运行它,并且获得了良好的压缩比。