背景
HDF5で日本語を保存したとき
b'\xe3\x81\x82\xe3\x81\x84\xe3\x81\x86'
のような出力になってしまい困っていたのですが、解決できまちた
が、より良い方法があればご教授いただけると幸いです٩( 'ω' )و
そしてPythonを普段使わないのでマズイことしてたらご指摘くださいませ
バージョン情報
python:3.6.1
h5py:2.7.0
※ Dockerで動かしています
コード
出力時にdecode('utf-8')
でデコードを行うことで解決できました。
import h5py
with h5py.File('sample_dataset.hdf5', mode='w') as f:
# vlen=str でないとUnicode文字が使えないので注意
str_dtype = h5py.special_dtype(vlen=str)
dataset = f.create_dataset(
'str_dataset', shape=(1,1), dtype=str_dtype)
dataset[0,0] = 'あいう'
# 以下の形式でhdf5ファイルに保存
# b'\xe3\x81\x82\xe3\x81\x84\xe3\x81\x86'
with h5py.File("sample_dataset.hdf5", "r") as f:
data = f["str_dataset"][0,0]
# 出力時にデコードを行う
print(data.decode('utf-8'))
print(data)
# 出力:あいう
参考