简体   繁体   中英

Python: split line by comma, then by space

I'm using Python 3 and I need to parse a line like this

-1 0 1 0 , -1 0 0 1

I want to split this into two lists using Fraction so that I can also parse entries like

1/2 17/12 , 1 0 1 1

My program uses a structure like this

from sys import stdin
...
functions'n'stuff
...
for line in stdin:

and I'm trying to do

for line in stdin:
X = [str(elem) for elem in line.split(" , ")]
num = [Fraction(elem) for elem in X[0].split()]
den = [Fraction(elem) for elem in X[1].split()]

but all I get is a list index out of range error: den = [Fraction(elem) for elem in X[1].split()] IndexError: list index out of range

I don't get it. I get a string from line . I split that string into two strings at " , " and should get one list X containing two strings. These I split at the whitespace into two separate lists while converting each element into Fraction . What am I missing?
I also tried adding X[-1] = X[-1].strip() to get rid of \\n that I get from ending the line.

The problem is that your file has a line without a " , " in it, so the split doesn't return 2 elements.

I'd use split(',') instead, and then use strip to remove the leading and trailing blanks. Note that str(...) is redundant, split already returns strings.

X = [elem.strip() for elem in line.split(",")]

You might also have a blank line at the end of the file, which would still only produce one result for split , so you should have a way to handle that case.

With valid input, your code actually works.

You probably get an invalid line, with too much space or even an empty line or so. So first thing inside the loop, print line . Then you know what's going on, you can see right above the error message what the problematic line was.

Or maybe you're not using stdin right. Write the input lines in a file, make sure you only have valid lines (especially no empty lines). Then feed it into your script:

python myscript.py < test.txt

How about this one:

pairs = [line.split(",") for line in stdin]
num = [fraction(elem[0]) for elem in pairs if len(elem) == 2]
den = [fraction(elem[1]) for elem in pairs if len(elem) == 2]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM