我认为我在调用 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/