Reading FORTRAN formatted numbers using Python

I need to read a data file containing numbers formatted by the (very) old FORTRAN style. The file line is as follows:

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

The file (or most of it) contains these numbers in a fixed-width format. The problem with reading these numbers in Python is that there is no E in these numbers. See 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 

I can write a parser to read this, but wanted to know if this has already been done. This is the old FORTRAN format, so I thought that maybe someone already understood this. Does anyone know a library to read such numbers?

+4
source share
3 answers

this should work:

 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] 
+1
source

You can use regex to insert "E" before passing numbers to the float .

 re.sub(r'(\d)([-+])', r'\1E\2', number) 
+5
source

You can use the Fortran Format library for Python as follows:

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

This library has been thoroughly tested using the Intel ifort 9.1 compiler to exactly match some more complex FORTRAN text-based IO formats.

Install with

 pip install fortranformat 

I have to declare an offset since I wrote this library ...

+2
source

Source: https://habr.com/ru/post/1444620/


All Articles