使用 Python 读取 FORTRAN 格式的数字

编程入门 行业动态 更新时间:2024-10-28 13:29:20
问题描述

我必须读取一个数据文件,其中包含以(非常)旧的 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]
  • 0
  • 0
  • 0
  • 0
  • 0

更多推荐

使用 Python 读取 FORTRAN 格式的数字

本文发布于:2023-05-22 18:57:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1326174.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!