【问题标题】:How do you create a compressed dataset in pytables that can store a Unicode string?如何在可存储 Unicode 字符串的 pytables 中创建压缩数据集?
【发布时间】:2014-01-14 23:33:19
【问题描述】:

我正在使用 PyTables 存储一个数据数组,效果很好;除此之外,我还需要存储一个包含 JSON 数据的中等大小 (50K-100K) Unicode 字符串,并且我想对其进行压缩。

如何在 PyTables 中做到这一点?自从我使用 HDF5 以来已经有很长时间了,我不记得存储字符数组以便可以压缩它们的正确方法。 (而且我似乎在 PyTables 网站上找不到类似的示例。)

【问题讨论】:

    标签: python string unicode compression pytables


    【解决方案1】:

    PyTables 本身不支持 unicode - 还没有。存储 unicode。首先将字符串转换为字节,然后存储长度为 1 的字符串或 uint8 的 VLArray。要获得压缩,只需使用具有非零 complevelFilters 实例来实例化您的数组。

    我所知道的所有像这样存储 JSON 数据的示例都是使用 HDF5 C-API 进行的。

    【讨论】:

    • 只是好奇,为什么是 VLArray 而不是 CArray 或 EArray?我还在学习 API,所以这对我来说是陌生的领域。
    • VL 是指元素的长度为“可变长度”。在 Arrays、CArrays、EArrays 和 Tables 中,所有元素或行的长度/大小必须完全相同。由于您无法确保所有数据的字节大小都相同(因为 unicode 的工作原理),并且选择最长的字符串作为所有成员的长度是一种浪费,因此最好使用可变长度数据结构。跨度>
    【解决方案2】:

    好的,根据 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 范围内的字符串运行它,并且获得了良好的压缩比。

    【讨论】:

    • The binary mode of fromstring is deprecated, as it behaves surprisingly on unicode inputs. Use frombuffer instead
    猜你喜欢
    • 2011-05-19
    • 2017-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-25
    • 2015-05-28
    • 2013-12-05
    相关资源
    最近更新 更多