1

I need to parse a line like these:

foo, bar > 1.0, baz = 2.0
foo  bar > 1.0  baz = 2.0
foo, bar, baz
foo  bar  baz

for each element it can be $string (>|<|<=|>=|=) $num or just $string, separator ',' is optional between the elements.

in all these cases, recognize them as:

['foo', 'bar', 'baz']

how could I do this in python?

1
  • What happens if there is only foo, bar or bar > 1.0 baz = 2.0 in a line? Commented Nov 17, 2013 at 9:23

3 Answers 3

3

You can split at every non alphabetic characters

re.split("[^a-zA-Z]+",input)

Though am assuming that your $string contain only alphabets..


You can remove empty results with filter

filter(None, str_list)
Sign up to request clarification or add additional context in comments.

Comments

2

You can just extract all the letter groups:

s = """
foo, bar > 1.0, baz = 2.0
foo  bar > 1.0  baz = 2.0
foo, bar, baz
foo  bar  baz
"""

import re
regex = re.compile(r'([a-z]+)', re.I)  # re.I (ignore case flag)

for line in s.splitlines():
    if not line:
        continue # skip empty lines

    print regex.findall(line)

>>> 
['foo', 'bar', 'baz']
['foo', 'bar', 'baz']
['foo', 'bar', 'baz']
['foo', 'bar', 'baz']

2 Comments

should probably be [a-zA-Z]+ to include capitals as well, no?
Or use the ignorecase flag.
0

This one checks for the syntax also:

import re
with open("input") as f:
    for line in f:
        line = line.strip()
        # chop a line into expressions of the form: str [OP NUMBER]
        exprs = re.split(r'(\w+\s*(?:[!<>=]=?\s*[\d.]*)?\s*,?\s*)', line)
        for expr in exprs:
            # chop each expression into tokens and get the str part
            tokens = re.findall(r'(\w+)\s*(?:[!<>=]=?\s*[\d.]*)?,?', expr)
            if tokens: print tokens

1 Comment

This is very close to what I want, my question is not well described, it should be str [OP str], and str can contains number too, I'm trying to figure out a solution based on your answer, thanks very much.

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.