0

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

1

2 Answers 2

1

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]
Sign up to request clarification or add additional context in comments.

2 Comments

Unfortunately all the lines are not similar. They are something like this : 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
Then best use a function. I have updated the script.
0

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)

8 Comments

missed the first digit
Variables are not differentiated with =! I just realised. Give me a moment!
@KeerthanaPrabhakaran it works partially though. My input line is just a set of values but you have taken it as a string ' '. I have a whole file with 100+ input lines like these. How to take them as a string?
This works too! >>> s='Y-342.33' >>> re.findall("(?<=[AZaz])?[0-9.+-]+",s) ['-342.33']
When you read the lines of your file, it is read as string and hence that shouldn't be a problem. Can you please share a sample IO!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.