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 に答える