Home > other >  Negative Values of Scientific Notation in TXT file
Negative Values of Scientific Notation in TXT file

Time:12-15

I have a TXT file with a mixed floating numbers as a string represented lists. When I convert each element as a list of float numbers, negative scientific values do not appear in the new list. For example, when I have the following values:

line1 : [119.       114.        67.       117.706474 113.051278  69.933043]
line2 : [ 1.20000000e 02  0.00000000e 00  6.70000000e 01  1.20217686e 02
line3 : -8.89000000e-04  7.03216110e 01]

my output is

line1 : [119.       114.        67.       117.706474 113.051278  69.933043]
line2 : [ 1.20000000e 02  0.00000000e 00  6.70000000e 01  1.20217686e 02]

As you see the output does not show the numbers starting from negative value. How can I deal with this problem?

input_file = open('file.txt', 'r')
output_file = "new_file.txt"
lines = input_file.readlines()
#print(lines)


with open(output_file, "w") as filehandle:
  for line in lines:
      
      transformed_points = line.split('\n')
      a = transformed_points[0]
      #print(transformed_points[0].strip().replace('. ',','))
      a = a.replace('[', '').replace(']', '')
      floats = [float(x) for x in a.split()]
      filehandle.write(str(floats[3:5]) ' \n')

CodePudding user response:

Here is how you can manually read this.
Not the cleanest implementation but it works.
You can just use this as a function to process the raw data lines.

input_file = open('file.txt', 'r')
output = 'new_file.txt'
lines = input_file.read() 
# print(lines)

add = False
newlines=[]
for char in lines:
    if char == '[':
        add=True
        line = []
        continue
    if char ==']':
        add=False
        newlines.append(''.join(line))
        continue

    if char == '\n': continue
    if add == True: line.append(char)

newlines_float = [list(map(float,line.split())) for line in newlines]

for i in newlines_float:
   print(i)

input_file.close()

# the output of this is a nested list with float numbers.
# You can use f-string formatting to properly output this as you wish. 

This outputs

[119.0, 114.0, 67.0, 117.706474, 113.051278, 69.933043]
[120.0, 0.0, 67.0, 120.217686, -0.000889, 70.321611]

CodePudding user response:

i think the input_files's example string is consist of 3 lines

line1 : '[119.       114.        67.       117.706474 113.051278  69.933043]'
line2 : '[ 1.20000000e 02  0.00000000e 00  6.70000000e 01  1.20217686e 02'
line3 : '-8.89000000e-04  7.03216110e 01]'

so if you use

for line in lines:

the example line3 is splited from original line(line2)
please check this

  • Related