我试图从这种格式解析日期:
"11/2012-2014,2016,10/2012,11/2012-10/2014,2012-11/2012,“。
预期结果为((11,2012),(2014),(2016),(10,2012),.)不良价值观:“11”
但出了点问题。
month = Word(nums).setParseAction(self.validate_month)
year = Word(nums).setParseAction(self.validate_year)
date = Optional(month + Literal("/")) + year
date_range = Group(date + Optional(Literal("-") + date))
dates = date_range + ZeroOrMore(Literal(",") + date_range)
command = StringStart() + dates + StringEnd()我哪里错了?
谢谢
发布于 2016-01-15 15:12:59
要获得您想要的输出,您需要做一些事情:
见下面的评论和示例输出:
# if there is a problem in your parse actions, you will need to post them
month = Word(nums)#.setParseAction(self.validate_month)
year = Word(nums)#.setParseAction(self.validate_year)
# wrap date in a Group
#date = Optional(month + Suppress("/")) + year
date = Group(Optional(month + Suppress("/")) + year)
date_range = Group(date + Optional(Suppress("-") + date))
dates = date_range + ZeroOrMore(Suppress(",") + date_range)
# your expression for dates can be replaced with this pyparsing helper
# dates = delimitedList(date_range)
# The trailing ',' causes an exception because of your use of StringEnd()
command = StringStart() + dates + StringEnd()
test = "11/2012-2014,2016,10/2012,11/2012-10/2014,2012-11/2012"
# you can also use parseAll=True in place of tacking StringEnd
# onto the end of your parser
command.parseString(test, parseAll=True).pprint()打印
[[['11', '2012'], ['2014']],
[['2016']],
[['10', '2012']],
[['11', '2012'], ['10', '2014']],
[['2012'], ['11', '2012']]]https://stackoverflow.com/questions/34811789
复制相似问题