Reputation: 28511
I'm using PyParsing with the following code, to parse date strings:
from pyparsing import *
# Day details (day number, superscript and day name)
daynum = Word(nums, max=2)
superscript = oneOf("th rd st nd", caseless=True)
day = oneOf("Mon Monday Tue Tues Tuesday Wed Weds Wednesday Thu Thur Thurs Thursday Fri Friday Sat Saturday Sun Sunday", caseless=True)
full_day_string = Optional(day).suppress() & daynum + Optional(superscript).suppress()
# Month names, with abbreviations
month = oneOf("Jan January Feb February Mar March Apr April May Jun June Jul July Aug August Sep September Oct October Nov November Dec December", caseless=True)
# Year
year = Word(nums, exact=4)
# Full string
date = Each( [full_day_string("day"), Optional(month)("month"), Optional(year)("year")])
When I run the parser, and dump the resulting structure, I get the following:
In [2]: r = date.parseString("23rd Jan 2012")
In [3]: print r.dump()
['23', 'Jan', '2012']
- day: ['23']
The optional fields inside the Each clause seem to have been picked up correctly (you can see inside the list at the top), but they aren't being labelled like they're meant to be.
This works fine if I change the Each
to an And
.
Is this meant to work? Or am I doing something wrong here? I've seen this question: pyparsing, Each, results name, but I can't seem to see what the problem was that the answerer fixed.
Upvotes: 1
Views: 282
Reputation: 63709
As a workaround, change:
date = Each( [full_day_string("day"), Optional(month)("month"), Optional(year)("year")])
to
date = Each( [full_day_string("day"), Optional(month("month")), Optional(year("year"))])
But this just tells me there's a bug in pyparsing. I've looked at it a bit, and have not found it yet. I'll post a new comment when I run it down.
Upvotes: 4