我想使用Python处理文件中的以下行(Fortran程序的输出):
74 0.4131493371345440E-03 -0.4592776407685850E-03 -0.1725046324754540
并获得一个数组,例如:
[74,0.4131493371345440e-3,-0.4592776407685850E-03,-0.1725046324754540]
我以前的尝试不起作用。特别是,如果我执行以下操作:
with open(filename,"r") as myfile:
line=np.array(re.findall(r"[-+]?\d*\.*\d+",myfile.readline())).astype(float)
我遇到以下错误:
ValueError: could not convert string to float: 'E-03'
答案 0 :(得分:0)
步骤:
str.split(' ')
)del arr[-1]
)代码:
import decimal # you may also leave this out and use `float` instead of `decimal.Decimal()`
arr = "74 0.4131493371345440E-03 -0.4592776407685850E-03 -0.1725046324754540 \n"
arr = arr.split(' ')
del arr[-1]
arr = [decimal.Decimal(x) for x in arr]
# do your np stuff
结果:
>>> print(arr)
[Decimal('74'), Decimal('0.0004131493371345440'), Decimal('-0.0004592776407685850'), Decimal('-0.1725046324754540')]
PS:
float()
/ decimal.Decimal()
数组代替。答案 1 :(得分:0)
@ ant.kr这是一个可能的解决方案:
# Initial data
a = "74 0.4131493371345440E-03 -0.4592776407685850E-03 -0.1725046324754540 \n"
# Given the structure of the initial data, we can proceed as follow:
# - split the initial at each white space; this will produce **list** with the last
# the element being **\n**
# - we can now convert each list element into a floating point data, store them in a
# numpy array.
line = np.array([float(i) for i in a.split(" ")[:-1]])