Prasanth
Prasanth

Reputation: 11

read only numbers from text file in python

I have a text file with the following entries:

 Y-6.352 Z281.116 A3=-1.0 B3=0.0 C3=0.0

I want only the numbers of each variable as follows:

 -6.352 281.116 -1.0 0.0 0.0

Any suggestions on how to approach this? I am new to python and couldn't figure a function to work this out. Any suggestions would be appreciated

Upvotes: 0

Views: 5020

Answers (2)

Martin Evans
Martin Evans

Reputation: 46789

So if your text file contains:

Y-6.352 Z281.116 A3=-1.0 B3=0.0 C3=0.0
Y-6.352 Z281.116 A3=-1.0 B3=0.0 C3=0.0 Y2.249 Z283.923 A3=-1.0 B3=0.0 C3=0.0

You could use the following non-regex approach:

def get_value(v):
    try:
        return float(v.split('=')[1])
    except IndexError as e:
        return float(v[1:])

with open('input.txt') as f_input:
    for raw_row in f_input:
        values = map(get_value, raw_row.split())
        print values

Giving you:

[-6.352, 281.116, -1.0, 0.0, 0.0]
[-6.352, 281.116, -1.0, 0.0, 0.0, 2.249, 283.923, -1.0, 0.0, 0.0]

Upvotes: 1

Keerthana Prabhakaran
Keerthana Prabhakaran

Reputation: 3787

Say s is the line of your file, you can use lookbehind assertion. ?<= to check for variables!

>>> import re
>>> s
'Y-6.352 Z281.116 A3=-1.0 B3=0.0 C3=0.0'
>>> re.findall("(?<=[AZaz])?(?!\d*=)[0-9.+-]+",s)
['-6.352', '281.116', '-1.0', '0.0', '0.0']

If you want to do the same with files,

import re
with open('input file.txt','r') as file:
    for line in file:
        print re.findall("(?<=[AZaz])?(?!\d*=)[0-9.+-]+",line)

Upvotes: 0

Related Questions