用科学数字(如0.4E03)读一行

2024-04-20 14:19:22 发布

您现在位置: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'

Tags: 文件程序reaswithnpline数组
2条回答

步骤:

代码:

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

附言:

  • 我不知道您是否首先编写了提供输出的文件,但是如果编写了,您可以考虑从该文件输出一个float()/decimal.Decimal()数组。你知道吗

你知道吗@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]])

相关问题 更多 >