首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >句法分析-解析日期

句法分析-解析日期
EN

Stack Overflow用户
提问于 2016-01-15 13:07:41
回答 1查看 908关注 0票数 4

我试图从这种格式解析日期:

"11/2012-2014,2016,10/2012,11/2012-10/2014,2012-11/2012,“。

预期结果为((11,2012),(2014),(2016),(10,2012),.)不良价值观:“11”

但出了点问题。

代码语言:javascript
复制
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()

我哪里错了?

谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-01-15 15:12:59

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

  • 在日期表达式周围添加组
  • 通过使用抑制而不是文字来抑制输出中的标点符号。

见下面的评论和示例输出:

代码语言:javascript
复制
# 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()

打印

代码语言:javascript
复制
[[['11', '2012'], ['2014']],
 [['2016']],
 [['10', '2012']],
 [['11', '2012'], ['10', '2014']],
 [['2012'], ['11', '2012']]]
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34811789

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档