用Python读取FORTRAN格式化的数字 [英] Read FORTRAN formatted numbers with Python

查看:398
本文介绍了用Python读取FORTRAN格式化的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have to read a data file that contains numbers formatted with (very) old FORTRAN style. A line of the file looks like this:

 4.500000+1 1.894719-3 4.600000+1 8.196721-3 4.700000+1 2.869539-3

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

The file (or large portion of it) contains these numbers in a fixed width format. The trouble with reading these numbers in Python is that there is no E in these numbers. Watch what happens:

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

我可以编写解析器读这个,但想知道这是否已经完成。这是一个古老的FORTRAN格式,所以我想也许有人已经弄明白了。有没有人知道图书馆读取这样的数字?

I can write a parser to read this, but wanted to know if this has already be done. This is an old FORTRAN format so I thought perhaps someone had already figured it out. Does anyone know of a library to read numbers like this?

推荐答案

这应该是工作:

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]

这篇关于用Python读取FORTRAN格式化的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆