我正在尝试加载存储在单个文本文件中的多个向量和矩阵(用于numpy)。 该文件如下所示:
%VectorA
1 2 3 4
%MatrixA
1 2 3
4 5 6
%VectorB
3 4 5 6 7
理想的解决方案是拥有一个字典对象,如:
{'VectorB': [3, 4, 5, 6, 7], 'VectorA': [1, 2, 3, 4], 'MatrixA':[[1, 2, 3],[4, 5, 6]]}
变量的顺序可以假定为固定的。因此,文本文件中出现顺序的numpy数组列表也可以。
答案 0 :(得分:5)
from StringIO import StringIO
mytext='''%VectorA
1 2 3 4
%MatrixA
1 2 3
4 5 6
%VectorB
3 4 5 6 7'''
myfile=StringIO(mytext)
mydict={}
for x in myfile.readlines():
if x.startswith('%'):
mydict.setdefault(x.strip('%').strip(),[])
lastkey=x.strip('%').strip()
else:
mydict[lastkey].append([int(x1) for x1 in x.split(' ')])
以上mydict
为:
{'MatrixA': [[1, 2, 3], [4, 5, 6]],
'VectorA': [[1, 2, 3, 4]],
'VectorB': [[3, 4, 5, 6, 7]]}