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.


Need Your Help

Firing RelayCommand from CodeBehind bound to VM

.net wpf mvvm mvvm-light relaycommand

I wonder if I can create a RelayCommand on my ViewModel like this:

Is it possible to hide a library dependency if it's a template class?

c++ templates

I have a library A that uses library B. I want the user of A to use a templated class from B library. But A and B have different namespaces, is it possible to encapsulate/hide that class from B in A

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.