LoginSignup
2
1

More than 1 year has passed since last update.

【Python】HDF5で日本語出力ができなくて困った件

Posted at

背景

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)
    # 出力:あいう

参考

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1