Python 数学公式中点积算子的替换
如何将点积(@)的pythons内部符号替换为numpy的numpy.dot?例如,公式Python 数学公式中点积算子的替换,python,regex,replace,Python,Regex,Replace,如何将点积(@)的pythons内部符号替换为numpy的numpy.dot?例如,公式 m。a@x+m。b@y应转换为np.dot(m.a,x)+np.dot(m.b,y) 我最初的想法是使用regex查找@前后的文本(m.a和m.b,在上面的示例中),然后将它们放在dot函数中。下面是我对使用正则表达式进行操作的想象: # m.a, m.b, x and y are vectors of some equal size formula = "m.a@x + m.b@y" before_dot
m。a@x+m。b@y
应转换为np.dot(m.a,x)+np.dot(m.b,y)
我最初的想法是使用regex查找@前后的文本(m.a
和m.b
,在上面的示例中),然后将它们放在dot函数中。下面是我对使用正则表达式进行操作的想象:
# m.a, m.b, x and y are vectors of some equal size
formula = "m.a@x + m.b@y"
before_dots, after_dots = some_regex_function(formula)
result = eval(f"np.dot({before_dot[0]},{after_dot[0]}) + np.dot({before_dot[1]},{after_dot[1]})")
使用
ast
和astor
模块,您可以解析代码并用np.dot
调用替换所有二进制运算节点,其中运算符是矩阵乘法
import ast
import astor
class ReplaceNpDot(astor.TreeWalk):
def post_BinOp(self):
node = self.cur_node
if isinstance(node.op, ast.MatMult):
np = ast.Name(id="np", ctx=ast.Load())
np_dot = ast.Attribute(np, 'dot', ctx=ast.Load())
self.replace(ast.Call(
np_dot,
args=[node.left, node.right],
keywords=[],
startargs=[]
))
else:
return node
# define m so it works...
# ...
# replace @ with np.dot
tree = ast.parse("m.a@x + m.b@y", mode='eval')
walker = ReplaceNpDot()
walker.walk(tree)
# print source code
print(astor.to_source(tree))
# run code
code = compile(ast.fix_missing_locations(tree), '<string>', 'eval')
exec(code)
导入ast
进口阿斯特
类替换点(astor.TreeWalk):
def post_BinOp(自):
node=self.cur\u节点
如果isinstance(node.op,ast.MatMult):
np=ast.Name(id=“np”,ctx=ast.Load())
np_dot=ast.Attribute(np'dot',ctx=ast.Load())
自我更换(ast.Call)(
np_点,
args=[node.left,node.right],
关键词=[],
startargs=[]
))
其他:
返回节点
#定义m使其工作。。。
# ...
#用np.dot替换@
tree=ast.parse(“m。a@x+m。b@y“,mode='eval')
walker=ReplaceNpDot()
步行者(树)
#打印源代码
打印(astor.to_源(树))
#运行代码
代码=编译(ast.fix\u缺少位置(树),“”,“eval”)
行政主任(代码)
使用正则表达式确实可以解决您所寻求的问题,但只有当您试图一次在多个文件中执行此操作时才有意义。此外,这些文件中应该没有电子邮件,因为电子邮件是这个正则表达式模式的一个子集,几乎总是匹配的 是我写的正则表达式,希望能涵盖所有可能的情况 要对多个文件执行此操作,我建议将其与
perl
一起使用
perl-i-pe的/(?不清楚您为什么使用正则表达式。如果您展示您的尝试,也许我们可以更好地理解以帮助您。您尝试了什么?到底是什么问题?@mkrieger1@可能不是Python中的运算符,但是如果您执行x@y对于某些向量x和y,你不需要修饰,而是计算x和y的点积。对不起,我错了,@
是确实是在Python 3.5中引入的。@mkrieger1我更新了这个问题,也许我想做的事情更清楚了。我意识到这肯定是混淆了,因为我在谈论字符串和点积。我正在使用eval
进行计算