如何在pyparsing中指定“无匹配”的键值?

2024-06-28 11:43:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我想让'pyparsing'解析结果作为字典出来,而不需要后期处理。为此,我需要定义自己的键字符串。以下是我能想到的最好的结果。在

要分析的行:

%ADD22C,0.35X*%

代码:

^{pr2}$

结果是:

['aperture-definition', '20', ['circle', ['diameter', '0.35']]]

我认为黑客攻击是

pyp.Empty().setParseAction(pyp.replaceWith('diameter'))

它总是匹配的并且是空的,但是我给它分配了我想要的键名。在

这是最好的办法吗?我是不是在滥用pyparsing来做它不该做的事情?在


Tags: 字符串代码字典定义pyparsingemptypypcircle
2条回答

如果要将floatnum命名为“diameter”,可以使用named results

cmd_app_def_opt_circ = pyp.Group(pyp.Literal('C') +
comma)("circle")


circular_apperture = pyp.Group(cmd_app_def_opt_circ +
pyp.Group(floatnum)("diameter") +
pyp.Literal('X').suppress())

这样,每次解析在circular_appertur上下文中遇到floatnum,这个结果就被命名为diameter。另外,如上所述,您可以用相同的方式命名circle。这对你有用吗?在

请参阅已发布代码中的注释。在

import pyparsing as pyp

comma = pyp.Literal(',').suppress()
# use parse actions to do type conversion at parse time, so that results fields
# can immediately be used as ints or floats, without additional int() or float()
# calls
floatnum = pyp.Regex(r'([\d\.]+)').setParseAction(lambda t: float(t[0]))
integer = pyp.Word(pyp.nums).setParseAction(lambda t: int(t[0]))

# define the command keyword - I assume there will be other commands too, they
# should follow this general pattern (define the command keyword, then all the
# options, then define the overall command)
aperture_defn_command_keyword = pyp.Literal('AD')

# define a results name for the matched integer - I don't know what this
# option is, wasn't in your original post
d_option = 'D' + integer.setResultsName('D')

# shortcut for defining a results name is to use the expression as a 
# callable, and pass the results name as the argument (I find this much
# cleaner and keeps the grammar definition from getting messy with lots
# of calls to setResultsName)
circular_aperture_defn = 'C' + comma + floatnum('diameter') + 'X'

# define the overall command
aperture_defn_command = aperture_defn_command_keyword("command") + d_option + pyp.Optional(circular_aperture_defn)

# use searchString to skip over '%'s and '*'s, gives us a ParseResults object
test = "%ADD22C,0.35X*%"
appData = aperture_defn_command.searchString(test)[0]

# ParseResults can be accessed directly just like a dict
print appData['command']
print appData['D']
print appData['diameter']

# or if you prefer attribute-style access to results names
print appData.command
print appData.D
print appData.diameter

# convert ParseResults to an actual Python dict, removes all unnamed tokens
print appData.asDict()

# dump() prints out the parsed tokens as a list, then all named results
print appData.dump()

印刷品:

^{pr2}$

相关问题 更多 >