我正在尝试编写 Lark 语法和解析器以在 numpy 之上编写 DSL。然而,Transformer 需要输出 Python 代码,而不是评估该代码。因此,例如,我想要:
my_parser("max(mat1/mat2, 20) / lag(mat1, 5)")
这将产生一个字符串:
'''
v0 = mat1
v1 = mat2
v2 = v0/v1
v3 = np.max(v2[-20:, :], axis=0)
v4 = mat1
v5 = v4[-5, :]
v6 = v3/v5
'''
哪里mat1
和mat2
是已知的numpy矩阵。我正在尝试:
这给了
from __future__ import print_function
import itertools
from lark import Lark, Transformer
grammar = r"""
?value: list
| max
| mat1
| mat2
| lag
| div
| max
| SIGNED_NUMBER
| ESCAPED_STRING
list : "(" [value ("," value)*] ")"
lag: "lag" "(" value "," SIGNED_NUMBER ")"
mat1: "mat1"
mat2: "mat2"
max: "max" "(" value "," SIGNED_NUMBER ")"
div: value "/" value
%import common.SIGNED_NUMBER
%import common.ESCAPED_STRING
%import common.WS
%ignore WS
"""
class MyTransformer(Transformer):
vcounter = itertools.count()
def __init__(self):
self.nplist = []
def list(self):
pass
def mat1(self, items):
thisv = self.vcounter.next()
self.nplist.append(
"v" + str(thisv) + " = mat1"
)
def mat2(self, items):
thisv = self.vcounter.next()
self.nplist.append(
"v" + str(thisv) + " = mat2"
)
def div(self, items):
thisv = self.vcounter.next()
self.nplist.append(
"v" + str(thisv) + " = v" + str(thisv - 2) + "/v" + str(thisv-1)
)
def lag(self, items):
thisv = self.vcounter.next()
self.nplist.append(
"v" + str(thisv) + " = v" + str(thisv -1) + "[-" + items[1] + ", :]"
)
def max(self, items):
thisv = self.vcounter.next()
self.nplist.append(
"v" + str(thisv) + " = np.max(v" + str(thisv-1) + "[-" + items[1] +":, :], axis=0)"
)
def transform(self, tree):
self._transform_tree(tree)
return self.nplist
my_parser = Lark(grammar, start='value')
text = "max(mat1/mat2, 20) / lag(mat1, 5)"
tree = my_parser.parse(text)
print(*MyTransformer().transform(tree), sep='\n')
这给了
v0 = mat1
v1 = mat2
v2 = v0/v1
v3 = np.max(v2[-20:, :], axis=0)
v4 = mat1
v5 = v4[-5, :]
v6 = v4/v5
这非常接近!
提前感谢您的任何指导。