2016-10-10 81 views
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) 

除非有这样做的更快的方法则,这是我怎么会那样做。我在下面的答案中也会采纳尼尔斯沃纳的建议。

回答

1

您应该使用

numpy.save('myData.npy', myData) 

然后你就可以读到这样

myData = numpy.load('myData.npy')