gpt4 book ai didi

Python/PyParsing : Difficulty with setResultsName

转载 作者:太空宇宙 更新时间:2023-11-03 14:34:54 24 4
gpt4 key购买 nike

我认为我在调用 setResultsName() 时犯了一个错误:

from pyparsing import *

DEPT_CODE = Regex(r'[A-Z]{2,}').setResultsName("Dept Code")
COURSE_NUMBER = Regex(r'[0-9]{4}').setResultsName("Course Number")

COURSE_NUMBER.setParseAction(lambda s, l, toks : int(toks[0]))

course = DEPT_CODE + COURSE_NUMBER

course.setResultsName("course")

statement = course

来自空闲:

>>> myparser import *
>>> statement.parseString("CS 2110")
(['CS', 2110], {'Dept Code': [('CS', 0)], 'Course Number': [(2110, 1)]})

我希望的输出:

>>> myparser import *
>>> statement.parseString("CS 2110")
(['CS', 2110], {'Course': ['CS', 2110], 'Dept Code': [('CS', 0)], 'Course Number': [(2110, 1)]})

setResultsName() 是否只对终端有效?

最佳答案

如果将course的定义改为

course = (DEPT_CODE + COURSE_NUMBER).setResultsName("Course")

你得到以下行为:

x=statement.parseString("CS 2110")
print(repr(x))
# (['CS', 2110], {'Course': [((['CS', 2110], {'Dept Code': [('CS', 0)], 'Course Number': [(2110, 1)]}), 0)], 'Dept Code': [('CS', 0)], 'Course Number': [(2110, 1)]})
print(x['Dept Code'])
# CS
print(x['Course Number'])
# 2110
print(x['Course'])
# ['CS', 2110]

这不是您想要的 repr,但这是否足够?

请注意,from the docs :

[setResultsName] returns a copy of the original ParserElement object; this is so that the client can define a basic element, such as an integer, and reference it in multiple places with different names.

因此 course.setResultsName("Course") 不起作用,因为它不影响 course。相反,您必须说 course=course.setResultsName("Course")。这是执行上述操作的另一种方法。

关于Python/PyParsing : Difficulty with setResultsName,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2940166/

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