首页 > 解决方案 > 用科学数字读取一行(如 0.4E-03)

问题描述

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

标签: python

解决方案


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

推荐阅读