从python中的文本文件读取多个变量的聪明方法 [英] smart way to read multiple variables from textfile in python

查看:187
本文介绍了从python中的文本文件读取多个变量的聪明方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试加载存储在单个文本文件中的多个向量和矩阵(用于numpy). 该文件如下所示:

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 3
4 5 6
%VectorB
3 4 5 6 7

理想的解决方案是使用像这样的字典对象:

The ideal solution would be to have a dictionary object like:

{'VectorB': [3, 4, 5, 6, 7], 'VectorA': [1, 2, 3, 4], 'MatrixA':[[1, 2, 3],[4, 5, 6]]}

变量的顺序可以假定为固定的.因此,按文本文件中出现顺序的numpy数组列表也可以.

The order of the variables can be assumed as fixed. So, a list of the numpy arrays in the order of appearance in the text file would also be okay.

推荐答案

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]]}

这篇关于从python中的文本文件读取多个变量的聪明方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆