動作環境
GeForce GTX 1070 (8GB)
ASRock Z170M Pro4S [Intel Z170chipset]
Ubuntu 16.04 LTS desktop amd64
TensorFlow v1.1.0
cuDNN v5.1 for Linux
CUDA v8.0
Python 3.5.2
IPython 6.0.0 -- An enhanced Interactive Python.
gcc (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609
GNU bash, version 4.3.48(1)-release (x86_64-pc-linux-gnu)
希望動作
ファイルの形式を変換する。
- ファイルヘッダを追加
- カンマ区切りをスペース区切りに変換する
input
inp_comma_170603.txt
1.0,2.0,3.0
4.0,5.0,6.0
7.0,8.0,9.0
output
out_space_170603.txt
A B C
1.0 2.0 3.0
4.0 5.0 6.0
7.0 8.0 9.0
v0.1
とりあえずリダイレクトを用いるという方法での実装。
code
comma_to_tabWithTitle_170603.py
import numpy as np
'''
v0.1 Jun. 03, 2017
- output as [standard output]
'''
# Python 3.5.2
# coding rule:PEP8
FILE_HEADER = "A B C"
data = np.genfromtxt('inp_comma_170603.txt', delimiter=',')
xpos, ypos, zpos = data[:, 0], data[:, 1], data[:, 2]
print(FILE_HEADER)
for tpl in zip(xpos, ypos, zpos):
print("%s %s %s" % tpl)
実行例
$ python3 comma_to_tabWithTitle_170603.py > out_space_170603.txt
$ cat out_space_170603.txt
A B C
1.0 2.0 3.0
4.0 5.0 6.0
7.0 8.0 9.0
v0.2
リダイレクトでなく、コード内で指定したファイルに書き出すようにする。
リダイレクトの方が便利かもしれないが、Pythonの勉強もかねて。
参考
-
文字列(ファイルヘッダ)の書き出し
-
byte書き出し
code
comma_to_tabWithTitle_170603.py
import numpy as np
'''
v0.2 Jun. 03, 2017
- output as [file]
v0.1 Jun. 03, 2017
- output as [standard output]
'''
# Python 3.5.2
# coding rule:PEP8
FILE_HEADER = "A B C"
OUTFILE = "out_space_170603.txt"
# 1. read data
data = np.genfromtxt('inp_comma_170603.txt', delimiter=',')
xpos, ypos, zpos = data[:, 0], data[:, 1], data[:, 2]
# 2. write file header
hdr = np.array(FILE_HEADER).reshape(1,)
np.savetxt(OUTFILE, hdr, fmt="%s", delimiter=" ")
# 3. write data
tpl = xpos, ypos, zpos
with open(OUTFILE, 'ab') as f_handle:
np.savetxt(f_handle, tpl, fmt="%.1f", delimiter=" ")
実行
$ python3 comma_to_tabWithTitle_170603.py
$ cat out_space_170603.txt
A B C
1.0 4.0 7.0
2.0 5.0 8.0
3.0 6.0 9.0
v0.3
データに加工せずそのまま出力するなら、以下でも良い。
comma_to_tabWithTitle_170603.py
import numpy as np
'''
v0.3 Jun. 03, 2017
- refactor
v0.2 Jun. 03, 2017
- output as [file]
v0.1 Jun. 03, 2017
- output as [standard output]
'''
# Python 3.5.2
# coding rule:PEP8
FILE_HEADER = "A B C"
OUTFILE = "out_space_170603.txt"
# 1. read data
data = np.genfromtxt('inp_comma_170603.txt', delimiter=',')
# 2. write file header
hdr = np.array(FILE_HEADER).reshape(1,)
np.savetxt(OUTFILE, hdr, fmt="%s", delimiter=" ")
# 3. write data
with open(OUTFILE, 'ab') as f_handle:
np.savetxt(f_handle, data, fmt="%.1f", delimiter=" ")