i want to convert a string into a float with Python 3.10.
The problem is the format of the string. For example:
" 3.841-11"
which stands for 3.841e-011.
I tried the classical
float(" 3.841-11")
but this gives an error.
Just to change this one string is no solution, because i want to read a bigger file like this:
$$
$$ GRID Data
$$
GRID 1 -44.0332667.9 -2.55271
GRID 2 -39.1406667.9 -2.26907
GRID 3 -34.2481667.9 -1.98544
GRID 4 -29.3555667.9 -1.70181
GRID 5 -24.4629667.9 -1.41817
GRID 6 -19.5703667.9 -1.13454
GRID 7 -14.6777667.9 -.850903
GRID 8 -9.78516667.9 -.567269
GRID 9 -4.89258667.9 -.283634
GRID 10 3.055-13667.9 3.841-11
GRID 11 4.892579667.9 .2836343
This is my code:
def read_fem(location):
mesh = open(location, 'r').read().splitlines()
point = []
for i in range(1, len(mesh)):
if '$' not in mesh[i]:
if 'GRID' in mesh[i]:
number = int(mesh[i][8:16])
x = float(mesh[i][24:32])
y = float(mesh[i][32:40])
z = float(mesh[i][40:48])
point.append([number, x, y, z])
Grateful for every answer.
CodePudding user response:
Replace -
with e-
before converting to float
:
s = '3.841-11'
out = float(s.replace('-', 'e-'))
Output: 3.841e-11
A more generic approach if you can have e
as well could be to use a regex:
import re
s = '3.841 4'
out = float(re.sub(r'(?=[- ])', 'e', s))
Output: 38410.0
CodePudding user response:
The following program will:
- assume the file is named:
grid_data.txt
- look for hyphens surrounded by numbers eg.
3.841-11
and convert to3.841e-11
- ignore hyphens at the beginning of numbers eg.
-44.0332
The fix_float()
function is allowing the conversion to happen.
- The regex in use is
\d(-)\d
Code:
import re
pattern = re.compile(r'\d(-)\d')
def fix_float(m):
val = m.group(0).replace('-','e-')
return val
def read_fem(location):
mesh = open(location, 'r').read().splitlines()
point = []
for m in mesh:
if '$' not in m:
if 'GRID' in m:
number = int(m[8:16])
x = float(pattern.sub(fix_float, m[24:32]))
y = float(pattern.sub(fix_float, m[32:40]))
z = float(pattern.sub(fix_float, m[40:48]))
point.append([number, x, y, z])
return point
# Extract the data from the file
data = read_fem('grid_data.txt')
# Display the data
for point in data:
print(point)
Output:
[1, -44.0332, 667.9, -2.55271]
[2, -39.1406, 667.9, -2.26907]
[3, -34.2481, 667.9, -1.98544]
[4, -29.3555, 667.9, -1.70181]
[5, -24.4629, 667.9, -1.41817]
[6, -19.5703, 667.9, -1.13454]
[7, -14.6777, 667.9, -0.850903]
[8, -9.78516, 667.9, -0.567269]
[9, -4.89258, 667.9, -0.283634]
[10, 3.055e-13, 667.9, 3.841e-11]
[11, 4.892579, 667.9, 0.2836343]