尽管没有内置选项,但这里有几个选项.
您可能无法接受的解决方案
该解决方案可能属于您的“快速且肮脏的”类别,但是它有助于引导下一个解决方案.
删除值= [,最后一行(];),并全局替换all;一无所获:
-24.92 -23.66 -22.55
-24.77 -23.56 -22.45
-24.54 -23.64 -22.56
然后,您可以按以下方式使用numpy的loadtxt.
>>> import numpy as np
>>> A = np.loadtxt('data.m')
>>> A
array([[-24.92, -23.66, -22.55],
[-24.77, -23.56, -22.45],
[-24.54, -23.64, -22.56]])
您可能会接受的解决方案
在此解决方案中,我们创建了一种将输入数据强制转换为numpy loadtxt喜欢的形式(实际上与上述形式相同)的方法.
import StringIO
import numpy as np
def convert_m(fname):
with open(fname, 'r') as fin:
arrstr = fin.read()
arrstr = arrstr.split('[', 1)[-1] # remove the content up to the first '['
arrstr = arrstr.rsplit(']', 1)[0] # remove the content after ']'
arrstr = arrstr.replace(';', '\n') # replace ';' with newline
return StringIO.StringIO(arrstr)
现在我们有了,执行以下操作.
>>> np.loadtxt(convert_m('data.m'))
array([[-24.92, -23.66, -22.55],
[-24.77, -23.56, -22.45],
[-24.54, -23.64, -22.56]])