使用Python读取FORTRAN格式的数字

jlc*_*lin 5 python fortran

我必须读取一个包含用(非常)旧FORTRAN样式格式化的数字的数据文件.该文件的一行如下所示:

 4.500000+1 1.894719-3 4.600000+1 8.196721-3 4.700000+1 2.869539-3
Run Code Online (Sandbox Code Playgroud)

文件(或其大部分)以固定宽度格式包含这些数字.在Python中读取这些数字的麻烦E在于这些数字中没有.看看会发生什么:

>>> float('4.50000+1')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for float(): 4.50000+1
Run Code Online (Sandbox Code Playgroud)

我可以编写一个解析器来阅读它,但想知道这是否已经完成.这是一种旧的FORTRAN格式,所以我想也许有人已经弄清楚了.有谁知道图书馆要读这样的数字?

Bre*_*dan 7

你可以使用Fortran Format Library for Python,如下所示,

>>> import fortranformat as ff
>>> reader = ff.FortranRecordReader('(6F13.7)')
>>> reader.read(' 4.500000+1 1.894719-3 4.600000+1 8.196721-3 4.700000+1 2.869539-3')
[45.0, 0.001894719, 46.0, 0.008196721, 47.0, 0.002869539]
Run Code Online (Sandbox Code Playgroud)

该库已经过英特尔的ifort 9.1编译器的广泛测试,以匹配一些奇怪的FORTRAN文本IO.

安装使用

pip install fortranformat
Run Code Online (Sandbox Code Playgroud)

自从我写这个库以后,我应该宣布一个偏见...


Jam*_*arp 5

您可以使用正则表达式在传递数字之前插入"E" float.

re.sub(r'(\d)([-+])', r'\1E\2', number)
Run Code Online (Sandbox Code Playgroud)


Ash*_*ary 2

这应该有效:

In [47]: strs="4.500000+1 1.894719-3 4.600000+1 8.196721-3 4.700000+1 2.869539-3"

In [48]: [float(x.replace("+","e+").replace("-","e-")) for x in strs.split()]

Out[48]: [45.0, 0.001894719, 46.0, 0.008196721, 47.0, 0.002869539]
Run Code Online (Sandbox Code Playgroud)

  • 负数呢?-4.5000+1 (2认同)