Separating elements from a list according to preceding element

Paul McGuire ptmcg at austin.rr._bogus_.com
Sun Mar 5 17:02:41 EST 2006


"Rob Cowie" <cowie.rob at gmail.com> wrote in message
news:1141587629.918414.245530 at t39g2000cwt.googlegroups.com...
> I'm having a bit of trouble with this so any help would be gratefully
> recieved...
>
> After splitting up a url I have a string of the form
> 'tag1+tag2+tag3-tag4', or '-tag1-tag2' etc. The first tag will only be
> preceeded by an operator if it is a '-', if it is preceded by nothing,
> '+' is to be assumed.
>
> Using re.split, I can generate a list that looks thus:
> ['tag1', '+', 'tag2', '+', 'tag3', '-', 'tag4']
>
> I wish to derive two lists - each containing either tags to be
> included, or tags to be excluded. My idea was to take an element,
> examine what element precedes it and accordingly, insert it into the
> relevant list. However, I have not been successful.
>
> Is there a better way that I have not considered? If this method is
> suitable, how might I implement it?
>
> Thanks all,
>
> Rob Cowie
>
Here's how this would look with pyparsing  (download pyparsing at
http://pyparsing.sourceforge.net ):


data = 'tag1+tag2+tag3-tag4'

from pyparsing import *
tag = Word(alphas,alphanums)
incl = Literal("+").suppress()
excl = Literal("-").suppress()

inclQual = Optional(incl) + tag
exclQual = excl + tag
qualDef = OneOrMore(
inclQual.setResultsName("includes",listAllMatches=True ) |


                  exclQual.setResultsName("excludes",listAllMatches=True ) )

quals = qualDef.parseString(data)
print quals.includes
print quals.excludes


Prints out:

[['tag1'], ['tag2'], ['tag3']]
[['tag4']]

-- Paul





More information about the Python-list mailing list