python中从textfile读取多个变量的智能方法

2024-04-18 16:11:41 发布

您现在位置:Python中文网/ 问答频道 /正文

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

%VectorA
1 2 3 4
%MatrixA
1 2 3
4 5 6
%VectorB
3 4 5 6 7

理想的解决方案是使用dictionary对象,例如:

^{pr2}$

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


Tags: 文件对象numpydictionary顺序矩阵数组解决方案
1条回答
网友
1楼 · 发布于 2024-04-18 16:11:41
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为:

^{pr2}$

相关问题 更多 >