阅读具有科学数字的行(例如0.4E-03)

时间:2018-11-20 17:08:48

标签: python

我想使用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'

2 个答案:

答案 0 :(得分:0)

步骤:

代码:

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