Reputation: 44533
I'm new to PyParser, but am keen to use it if I can make it work.
I have message strings I'd like to parse that have a command verb, a multi word object name, and then an optional suffix, some examples:
verb object
verb another object
verb object friday
verb another object monday
The verbs are from a fixed list, and so are the suffixes (days of the week in this example), but the object names can be any other combination of words.
This strikes me as the kind of thing that should be pretty basic and so far I have:
#!/bin/env python
from pyparsing import Word, alphas, Group, OneOrMore, oneOf, Optional
Verb = Word(alphas)
Object = Group(OneOrMore(Word(alphas)))
Suffix = oneOf('Monday Tuesday Wednesday Thursday Friday Saturday Sunday',
caseless=True)
Command = Verb + Object + Optional(Suffix)
for msg in ["verb object",
"verb another object",
"verb object friday",
"verb another object monday"]:
print(Command.parseString(msg))
This isn't working how I want though, I'm getting the following output where Suffix is being included in the Object group:
['verb', ['object']]
['verb', ['another', 'object']]
['verb', ['object', 'friday']]
['verb', ['another', 'object', 'monday']]
I've tried using NotAny and a few other things but haven't got far, can someone please point me in the right direction?
Upvotes: 1
Views: 160
Reputation: 44533
Ok, I think I was using NotAny the wrong way, I had tried:
Object = Group(OneOrMore(Word(alphas) + NotAny(Suffix)))
But if I put the NotAny before the Word it works:
Object = Group(OneOrMore(NotAny(Suffix) + Word(alphas)))
Output is:
['verb', ['object']]
['verb', ['another', 'object']]
['verb', ['object'], 'Friday']
['verb', ['another', 'object'], 'Monday']
Seems pretty straight-forward, but I'm open to suggestions if there is a better way.
Upvotes: 1