首页 > 解决方案 > pyparsing - 如何解析逗号以在函数中使用

问题描述

所以我正在制作一个解析器,但该程序不解析逗号。例如:

>>> evaluate("round(pi)")
3

>>> evaluate("round(pi, 2)")
SyntaxError: Expected {{[- | +] {{{{{{{W:(ABCD..., ABCD...) Suppress:("(") : ...} Suppress:(")")} | 'PI'} | 'E'} | 'PHI'} | 'TAU'} | {Combine:({{W:(+-01..., 0123...) [{"." [W:(0123...)]}]} [{{'E' [W:(+-)]} W:(0123...)}]}) | Combine:({{{[W:(+-)] "."} W:(0123...)} [{{'E' [W:(+-)]} W:(0123...)}]})}}} | {[- | +] Group:({{Suppress:("(") : ...} Suppress:(")")})}}, found ','  (at
char 8), (line:1, col:9)

程序如何解析函数中使用的逗号?我的目标是round(pi, 2)返回3.14log(10, 10)返回之类的函数1.0

标签: pythonpython-3.xparsingpyparsing

解决方案


如果您有一个解析器解析括号中的单个整数,如下所示:

LPAR, RPAR = map(Suppress, "()")
integer = Word(nums)
int_values = LPAR + integer + RPAR

并且您想将其更改为接受整数列表,您可以编写:

int_values = LPAR + delimitedList(integer) + RPAR

您也可能会使用 Group 将这些解析的值逻辑地保持在一起:

int_values = LPAR + Group(delimitedList(integer)) + RPAR

推荐阅读