使用解析将**运算符更改为幂函数?
作者:互联网
我的要求是将**运算符更改为幂函数
例如
1.Input -"B**2"
Output - power(B,2)
2."B**2&&T**2*X"
Output - power(B,2)
我写了以下正则表达式来解决这个问题
rx=r"([a-zA-Z0-9]+)\*\*([a-zA-Z0-9()]+)"
result = regex.sub(rx, r"power(\1,\2)", expression, 0, regex.IGNORECASE | regex.MULTILINE)
但是上面的代码成功转换了类似于示例1和示例2的表达式,但是未能转换类似于(a 1)** 2或((a b)* c)** 2之类的表达式.我意识到正则表达式不是处理此类情况的最佳方法.代替该解析将是处理该问题的最佳方法.
我对python有点陌生.请指导我如何解决此问题.
解决方法:
这听起来很熟悉,我认为我在pyparsing邮件列表中处理了类似的问题,但目前找不到.但是尝试这样的事情:
from pyparsing import *
# define some basic operand expressions
number = Regex(r'\d+(\.\d*)?([Ee][+-]?\d+)?')
ident = Word(alphas+'_', alphanums+'_')
# forward declare our overall expression, since a slice could
# contain an arithmetic expression
expr = Forward()
slice_ref = '[' + expr + ']'
# define our arithmetic operand
operand = number | Combine(ident + Optional(slice_ref))
# parse actions to convert parsed items
def convert_to_pow(tokens):
tmp = tokens[0][:]
ret = tmp.pop(-1)
tmp.pop(-1)
while tmp:
base = tmp.pop(-1)
# hack to handle '**' precedence ahead of '-'
if base.startswith('-'):
ret = '-pow(%s,%s)' % (base[1:], ret)
else:
ret = 'pow(%s,%s)' % (base, ret)
if tmp:
tmp.pop(-1)
return ret
def unary_as_is(tokens):
return '(%s)' % ''.join(tokens[0])
def as_is(tokens):
return '%s' % ''.join(tokens[0])
# simplest infixNotation - may need to add a few more operators, but start with this for now
arith_expr = infixNotation( operand,
[
('-', 1, opAssoc.RIGHT, as_is),
('**', 2, opAssoc.LEFT, convert_to_pow),
('-', 1, opAssoc.RIGHT, unary_as_is),
(oneOf("* /"), 2, opAssoc.LEFT, as_is),
(oneOf("+ -"), 2, opAssoc.LEFT, as_is),
])
# now assign into forward-declared expr
expr <<= arith_expr.setParseAction(lambda t: '(%s)' % ''.join(t))
assert "2**3" == expr
assert "2**-3" == expr
# test it out
tests = [
"2**3",
"2**-3",
"2**3**x5",
"2**-3**x6[-1]",
"2**-3**x5+1",
"(a+1)**2",
"((a+b)*c)**2",
"B**2",
"-B**2",
"(-B)**2",
"B**-2",
"B**(-2)",
"B**2&&T**2*X",
]
x5 = 2
a,b,c = 1,2,3
B = 4
x6 = [3,2]
for test in tests:
print test
xform = expr.transformString(test)[1:-1]
print xform
print '**' not in xform and eval(xform) == eval(test)
print
打印:
2**3
pow(2,3)
True
2**-3
pow(2,-3)
True
2**3**x5
pow(2,pow(3,x5))
True
2**-3**x6[-1]
pow(2,-pow(3,x6[((-1))]))
True
2**-3**x5+1
pow(2,-pow(3,x5))+1
True
(a+1)**2
pow((a+1),2)
True
((a+b)*c)**2
pow(((a+b)*c),2)
True
B**2
pow(B,2)
True
-B**2
(-pow(B,2))
True
(-B)**2
pow(((-B)),2)
True
B**-2
pow(B,-2)
True
B**(-2)
pow(B,((-2)))
True
B**2&&T**2*X
pow(B,2))&&(pow(T,2)*X
Traceback (most recent call last):
File "convert_to_pow.py", line 85, in <module>
print '**' not in xform and eval(xform) == eval(test)
File "<string>", line 1
pow(B,2))&&(pow(T,2)*X
^
SyntaxError: invalid syntax
如果要转换的代码中有更多的极端情况,则可能只需要对操作数表达式进行一些调整,或者在infixNotation表达式中添加更多的运算符(例如&&&).
(请注意,您必须像写a **(b ** c)那样转换a ** b ** c,因为链式幂运算是从右到左而不是从左到右求值的.)
编辑:
引入了可正确处理“-”和“ **”之间优先级的hack.扩展测试以实际评估字符串之前/之后.现在看起来更加牢固.
标签:pyparsing,python,python-2-7,regex,abstract-syntax-tree 来源: https://codeday.me/bug/20191011/1895995.html