0
運7,64,的Python 2.7.12製表符分隔數組到numpy數組列表?
我在形式
myData = [[a1, b1, c1, d1, e1, f1, g1, h1], [a2, b2, c2, .... ], ..... ]
其中myData
是漂浮的np.ndarray
數據。我救了這個使用以下...
with open('myData.txt', 'w') as f:
for s in myData:
f.write(str(s) + '\n')
其中關於檢查竟是保存像...
[a1 b1 c1 d1 e1 f1 g1 h1]
[a2 b2 c2 d2 e2 f2 g2 h1]
.....
即分隔標籤。
所以,我想讀回使用...
import numpy as np
from ast import literal_eval
with open('myData.txt', 'r') as f:
fromFile = [np.ndarray(literal_eval(line)) for line in f]
f.close()
但是,這將引發一個錯誤......
File "<unknown>", line 1
[ 1. 1.198 2.063 1.833 1.458 1.885 1.969 0.343]
^
SyntaxError: invalid syntax
所以因爲我不能重新生成該文件myData.txt
如何恢復它到它的初始數據類型?
還有一種方法可以在第一時間停止寫入數據嗎?
編輯:一種解決上述...
import numpy as np
from ast import literal_eval
branches = ['[ 1. 1.198 2.063 1.833 1.458 1.885 1.969 0.343]\n',
'[ 2. 1.26 2. 1.26 1.26 2. 1.26 0. ]\n',
'[ 3. 1.688 2. 1.781 1.573 2.021 1.979 0.23 ]\n',
'[ 4. 1.604 2.729 1.792 1.667 2.49 1.948 0.293]\n']
branches = [line.rstrip(']\n') for line in branches]
branches = [line.lstrip('[ ') for line in branches]
print branches[0]
branches = [line.split(' ') for line in branches]
newBranches = []
for branch in branches:
branch = filter(None, branch)
branch = [float(item) for item in branch]
newBranches.append(branch)
print newBranches[0]
branches = np.array(newBranches)
除非有這樣做的更快的方法則,這是我怎麼會那樣做。我在下面的答案中也會採納尼爾斯沃納的建議。