gpt4 book ai didi

python - pyparsing - 解析日期

转载 作者:行者123 更新时间:2023-11-28 17:30:21 24 4
gpt4 key购买 nike


我正在尝试从这种格式解析日期:
"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()

我哪里错了?
谢谢

最佳答案

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

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

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

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

# 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']]]

关于python - pyparsing - 解析日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34811789/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com