我有一个很小的解析项目*病理学家在电子记录中写下他们的诊断。他们中的绝大多数使用“GLEASON SCORE:3 + 4 = 7”的形式,然而,有很多关于它的重复。一个我无法弄清楚如何应对的是“GLEASON SCORE:7 = 3 + 4”
到现在为止,我的语法已经
了gleason = Group("GLEASON" + Optional("SCORE") + Optional("GRADE") + Optional("PATTERN") + Optional(":") + num("left") + "+" + num("right") + Optional("=") + Optional("total"))
我尝试添加
... + Optional(":") + Optional(num("total")) + Optional("=") + ...
在“left”变量之前,但它只找到了缺失的记录,而不是所有的记录。我需要搜索模式A(a + b = c)或模式B(c = a + b)。我怎样才能在pyparsing中做到这一点?
答案 0 :(得分:3)
使用pyparsing的operatorPrecedence
来轻松定义4函数算术表达式,而不是使用nums和'+'滚动自己的算术表达式:
arith_expr = operatorPrecedence(num,
[
(oneOf('-'), 1, opAssoc.RIGHT),
(oneOf('* /'), 2, opAssoc.LEFT),
(oneOf('+ -'), 2, opAssoc.LEFT),
])
然后将num("left") + "+" + num("right") + Optional("=") + Optional(num)("total")
替换为:
arith_expr('lhs') + Optional('=' + arith_expr('rhs'))
现在,您将能够解析任何算术表达式,包括具有嵌套括号的算术表达式,而不仅仅是“x + y = z”类型表达式。
答案 1 :(得分:2)
>>> eqn = Word(alphas,exact=1)+"+"+Word(alphas,exact=1)+"="+Word(alphas,exact=1)
>>> eqn2 = Word(alphas,exact=1)+"="+Word(alphas,exact=1)+"+"+Word(alphas,exact=1
)
>>> equation = eqn|eqn2
>>> equation.parseString("A+b=c")
(['A', '+', 'b', '=', 'c'], {})
>>> equation.parseString("A=b+c")
(['A', '=', 'b', '+', 'c'], {})
>>> equation.parseString("A=b-c")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python26\lib\site-packages\pyparsing.py", line 1032, in parseString
raise exc
pyparsing.ParseException: Expected "+" (at char 3), (line:1, col:4)