pyparsing - 解析日期

时间:2016-01-15 13:07:41

标签: python pyparsing


我试图从这种格式解析日期:
“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()

我哪里错了?
感谢

1 个答案:

答案 0 :(得分:1)

要获得所需的输出,您需要做一些事情:

  • 在日期表达式周围添加组

  • 使用Suppress而不是Literal来抑制输出中的标点符号

请参阅以下评论和示例输出:

owl.owlCarousel({
    items: 3,
    navigation: false,
    navigationText: ["<img src='img/left.png'>",'<img src="img/right.png">'],
    slideSpeed: 300,
    paginationSpeed: 400,
    afterInit: afterOWLinit // do some work after OWL init
});

打印

# 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()