Read FORTRAN formatted numbers with Python

前端 未结 4 1487
一向
一向 2020-12-20 22:41

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         


        
相关标签:
4条回答
  • 2020-12-20 23:21

    You could 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 extensively tested aginst Intel's ifort 9.1 compiler to match exactly some of the weirder FORTRAN textual IO.

    Install using

    pip install fortranformat
    

    I should declare a bias since I wrote this library ...

    0 讨论(0)
  • 2020-12-20 23:23

    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]
    
    0 讨论(0)
  • 2020-12-20 23:31

    Another approach is to use a system command to access AWK:

    Note the escaping of the " characters inside COMMAND

    import subprocess
    COMMAND = "awk 'gsub(/D/,\"E\");{print}' epsc8.out > epsc8E.out"
    subprocess.call(COMMAND, shell=True)
    
    0 讨论(0)
  • 2020-12-20 23:43

    You could use a regular expression to insert the "E"s before passing the numbers to float.

    re.sub(r'(\d)([-+])', r'\1E\2', number)
    
    0 讨论(0)
提交回复
热议问题