3

我正在尝试加载存储在单个文本文件中的多个向量和矩阵(用于 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 数组列表也可以。

4

1 回答 1

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]]}
于 2013-04-17T11:13:14.787 回答