# Regex Help, por favor

So I have a text file with comma separated numbers, I'm trying to write Python to get me the numbers three at a time - they're 3D co-ordinates and I want to analyse them 3 at a time.

The text file is of the form

x1,y1,z1,x2,y2,...,

and is just one line.

Cheers.

## Answers

Yeah, Any comma separated data evinces the need for CSV but you could do with simple split here too.

Your comma separated string of (x, y, z) coordinates

>>> t = "x1,y1,z1,x2,y2,z2,x3,y3,z3"

Use split :

>>> t1 = t.split(',') >>> t1 ['x1', 'y1', 'z1', 'x2', 'y2', 'z2', 'x3', 'y3', 'z3']

Then collate / group the results into 3 elements. You will need to make sure that len(t1) is multiple of 3s. Use assert for that.

>>> t2 = [] >>> for x in range(len(t1)/3): t2.append(t1[x*3 : x*3+3]) ... >>> t2 [['x1', 'y1', 'z1'], ['x2', 'y2', 'z2'], ['x3', 'y3', 'z3']] >>>

You don't need regex for this. Check out the CSV module.

def coords(line): parts = line.split(',') for i in range(0, len(parts), 3): yield map(int, parts[i:i+3])

No need to resort to regexes, really.