Joan Lopez
Joan Lopez

Reputation: 119

Parse flat-file (positional text-file) to read a column

I have this code: the data is: element, ion, wavelength, data1, abundance.

txt='FI R       83.0000m   34.960    1.1262      Fe 2      1.32055m   33.626    0.0522      
N  2      5754.61A   33.290    0.0241
TI R       1800.00m   33.092    0.0153      Fe 2      1.24854m   32.645    0.0054      N  
2      915.612A   31.997    0.0012
NI Ra      2.85000m   36.291   24.1132      Fe 2      7637.54A   33.077    0.0147      N  
2      2139.01A   32.920    0.0103
NI Rb      3.00000m   35.765    7.1930      Fe 2      4889.62A   32.774    0.0073      N  
2      1084.58A   31.927    0.0010'

N2=re.findall('N  2.*?([0-9].*?)\s', text)

for value in N2:
    del_letters = re.sub('[A-Za-z]', '', value)
    float_value = float(del_letters)
    if (float_value >= 5700) and (float_value <=5800):
        print(value)

But this only gives me the third column, and i want to obtain the value of the 5 column which is 0.0241, i tried but i can't resolve

Upvotes: 1

Views: 213

Answers (1)

Raymond Hettinger
Raymond Hettinger

Reputation: 226534

String slicing can help extract the data.

Here is some code to get you started:

for r in txt.splitlines():
    fields = r[:2], r[3], float(r[6:18]), float(r[20:28])
    print(fields)

This outputs:

('FI', 'R', 83.0, 34.96)
('TI', 'R', 1800.0, 33.092)
('NI', 'R', 2.85, 36.291)
('NI', 'R', 3.0, 35.765)

Upvotes: 1

Related Questions