1

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.

4

1 回答 1

4

作为一种解决方法,更改:

date = Each( [full_day_string("day"), Optional(month)("month"), Optional(year)("year")])

date = Each( [full_day_string("day"), Optional(month("month")), Optional(year("year"))])

但这只是告诉我在 pyparsing 中有一个错误。我看了一点,还没有找到。当我运行它时,我会发布一条新评论。

于 2012-05-01T12:18:10.290 回答