2

I have an output from old code in Fortran 77. The output is written with

write(NUM,*)

line. So basically, default format. Following is part of output:

1.25107598E-67  1.89781536E-61  1.28064971E-94  5.85754394-118  8.02718071E-94 

I had a post-processing tool written in F77 and READ(NUM,*) read the input file correctly as:

1.25107598000000E-67  1.89781536000000E-61  1.28064971000000E-94  5.85754394000000E-118  8.02718071000000E-94

The problematic number is 5.85754394-118. It will read correctly as it means 5.85754394E-118 in F77.

However, now I wrote a post-processing in python and I have a following line of code:

Z = numpy.fromstring(lines[nl], dtype=float, sep=' ')

which will read an output line by line (through loop on nl). But when it reaches the 5.85754394-118 number it will stop reading, going to the next line of output and basically reading wrong number. Is there any way to read it in a correct way (default way of Fortran)? I will guess I need to change dtype option but not have any clue.

mko
  • 61
  • 7
  • you mean you fail to post-process your strangely formatted number? – Jean-François Fabre Nov 22 '16 at 12:26
  • Yes! that's right – mko Nov 22 '16 at 12:35
  • Are you able to slightly modify the Fortran code which writes the corrupt value? See http://stackoverflow.com/questions/24004824/for-three-digit-exponents-fortran-drops-the-e-in-the-output – John Zwinck Nov 22 '16 at 12:36
  • I can write a small post-processing file in F77 which read the previous output and write it in a float format which python likes. But I wanted something in python itself. If there is no way, then I will change a format. – mko Nov 22 '16 at 12:40

1 Answers1

4

You can post-process your output efficiently with a regular expression:

import re

r = re.compile(r"(?<=\d)\-(?=\d)")

output_line = "1.25107598E-67  1.89781536E-61  1.28064971E-94  5.85754394-118  8.02718071E-94 "
print(r.sub("E-",output_line))

result:

1.25107598E-67  1.89781536E-61  1.28064971E-94  5.85754394E-118  8.02718071E-94 

(?<=\d)\-(?=\d) performs a lookbehind and lookahead for digits, and search for single minus sign between them. It replaces the minus sign by E-.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219