I\'m trying to load multiple vectors and matrices (for numpy) that are stored in a single text file. The file looks like this:
%VectorA
1 2 3 4
%MatrixA
1 2
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(' ')])
above gives mydict
as:
{'MatrixA': [[1, 2, 3], [4, 5, 6]],
'VectorA': [[1, 2, 3, 4]],
'VectorB': [[3, 4, 5, 6, 7]]}