H5py存储字符串列表的列表

时间:2016-06-17 04:46:16

标签: python hdf5 h5py

h5py是否有可能创建一个由字符串列表组成的数据集。我试图创建一个可变长度的嵌套数据类型,但这会在我的python解释器中导致分段错误。

def create_dataset(h5py_file):
    data = [['I', 'am', 'a', 'sentecne'], ['another', 'sentence']]
    string_dt = h5py.special_dtype(vlen=str)
    nested_dt = h5py.special_dtype(vlen=string_dt)
    h5py_file.create_dataset("sentences", data=data, dtype = nested_dt)

2 个答案:

答案 0 :(得分:2)

如果您将数据定义为此post中建议的dtype = object的numpy数组,而不是列表列表,则应该能够获得所需的功能。

def create_dataset(h5py_file):
    data = np.array([['I', 'am', 'a', 'sentence'], ['another', 'sentence']], dtype=object)
    string_dt = h5py.special_dtype(vlen=str)
    h5py_file.create_dataset("sentences", data=data, dtype=string_dt)

答案 1 :(得分:2)

如果您不打算编辑hdf5文件(并且可能使用更长的字符串),您也可以使用:

h5py_file.create_dataset("sentences", data=np.array(data, dtype='S'))
相关问题