【问题标题】:Add string to h5 file将字符串添加到 h5 文件
【发布时间】:2016-06-06 16:08:23
【问题描述】:

我有以下代码:

import tables
import numpy as np

filename = "file.h5"

x = np.random.random(150)
z = np.random.random(150)
mystr = " " * 160

f = tables.open_file(filename, mode="w")
hds = f.create_carray(f.root, "x", obj=x, 
                      filters=tables.Filters(complevel=5, complib='zlib'))
hds = f.create_carray(f.root, "z", obj=z, 
                      filters=tables.Filters(complevel=5, complib='zlib'))                
f.close()

我想在我的文件中添加一个长度为 160 的字符串。有没有一种优雅的方法可以做到这一点?

提前谢谢你。

【问题讨论】:

    标签: python string numpy pytables


    【解决方案1】:

    使用h5py,您可以将包含字符串(或仅一个字符串)的numpy 数组存储为数据集。或者,您可以将字符串存储为组或数据集的属性。

     http://docs.h5py.org/en/latest/strings.html
    

    可以这么简单:

    dset.attrs["title"] = "Hello"
    

    我没有使用过tables,但它也必须能够访问这些属性。文档中没有内容吗?

    文件对象本身也有一个.attrs 字典。

    【讨论】:

      【解决方案2】:

      在 H5 中存储字符串类型的数据有点棘手。这是第一次使用 Python 的 H5 用户的常见问题。在放入 H5 数据集之前必须清楚地显示数据类型(即,无论是字符串、整数还是浮点数)。至于字符串数据类型,需要指定为变量。例如,dt = h5py.string_dtype().

      下面是一个将字符串放入 H5 文件的示例。

      import h5py
      data = 'value in string'
      f= h5py.File('./fname.h5','w')
      try:
          dt = h5py.string_dtype()
          f.create_dataset('str_data', data=data, dtype=dt)
      except Exception as ex:
          print(ex)
      finally:
          f.close()
      

      另外,供您参考,要检查数据是否存储正确,只需使用以下代码。

      f= h5py.File('./fname.h5','r')
      try:
          print(f.keys())
          print(f['str_data'][()])
      except Exception as ex:
          print(ex)
      finally:
          f.close()
      

      如需进一步参考,请阅读有关 HDF5 中字符串的 H5 文档。 http://docs.h5py.org/en/stable/strings.html

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-02-16
        • 1970-01-01
        • 2017-02-07
        • 2022-11-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多