Reading fortran double precision format into python

点点圈 提交于 2019-12-19 02:30:15

问题


I am trying to read a Fortran double-precision number like 1.2345D+02 into python, but I got the following error:

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

By following the advice on Python scientific notation using D instead of E, I tried numpy but I also get the same error:

import numpy
>>> numpy.float("1.2345D+02")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for float(): 1.2345D+02

Is there a solution in Python to read those double precision numbers without just changing the 'D' to 'E'?

EDIT: I replaced a bad syntax on the strings. But still I get errors.


回答1:


What's wrong with float(str.replace("D", "E"))?

Please note, numpy DOES support fortran notation: numpy.float("1.2345D+02").

You seem to have some deeper purpose, perhaps shedding light on it would help.




回答2:


The substitution can be made a bit more careful by using a regular expression:

import re
re_dbl_fort = re.compile(r'(\d*\.\d+)[dD]([-+]?\d+)')

text = 'DEW=[0.242D+03 -4.320D-06]'
re_dbl_fort.sub(r'\1E\2', text)
# DEW=[0.242E+03 -4.320E-06]

Or if you have a list of strings (lines) read from a file using readlines():

lines = ['REPORT CARD\n', 'GRADE: D+ (1.3D+00/4.0D+00)\n']
for ln, line in enumerate(lines):
    res = re_dbl_fort.sub(r'\1E\2', line)
    if line != res:
        lines[ln] = res
# ['REPORT CARD\n', 'GRADE: D+ (1.3E+00/4.0E+00)\n']


来源:https://stackoverflow.com/questions/5989351/reading-fortran-double-precision-format-into-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!