我正在尝试加载存储在单个文本文件中的多个向量和矩阵(对于 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 数组也可以。
最佳答案
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 - 在 python 中从文本文件中读取多个变量的聪明方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16058020/