使用 python 在 hdf5 文件中变音

Umlauts in hdf5 files using python

我想使用 python hdf5.py 将字符串存储在 hdf5 文件中,只要 Unicode 字符串中没有变音符号或其他特殊字符,它就可以正常工作:

# -*- coding: utf-8 -*-

import h5py

dtype = h5py.special_dtype(vlen=unicode)
wdata = u"Ärger"

with h5py.File("test.h5", 'w') as f:
    dset = f.create_dataset("DS1", (1,), dtype=dtype)
    dset[...] = wdata


with h5py.File("test.h5") as f:
    rdata = f["DS1"].value
print rdata    

不是 Ärger,答案是 u'\xc4rger'

是否可以将变音符号存储在 hdf5 文件中?怎么样?

您需要为您的数据设置适用于 hdf5 的编码(并且可能会跟踪您正在使用的编码,以便您以后可以正确恢复数据)。从本质上讲,编码会将超出 ascii 范围的字符序列化为看起来像转义序列的内容——稍后可以将其转换回您的终端或其他地方可读的文本。

仅仅因为您在 Python 中使用了 u"" 字符串,并不意味着该字符串是以适用于这种情况的特定方式编码的。

hdf5 docs on using unicode

感谢您的帮助,以下代码有效,问题显然是数据集是数组,没有选择正确的元素:

# -*- coding: utf-8 -*-

import h5py

dtype = h5py.special_dtype(vlen=unicode)
wdata = u"umlauts, in HDF5, for example öüßÄ might cause trouble"

print wdata



with h5py.File("test.h5", 'w') as f:
    dset = f.create_dataset("DS1", (1,), dtype=dtype)
    dset[...] = wdata


with h5py.File("test.h5") as f:
    rdata = f["DS1"].value[-1]

print rdata

问候