smart way to read multiple variables from textfile in python

后端 未结 1 1223
别跟我提以往
别跟我提以往 2021-01-14 07:38

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          


        
相关标签:
1条回答
  • 2021-01-14 07:52
    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]]}
    
    0 讨论(0)
提交回复
热议问题