How to parse a function with ply in python?

问题描述 投票:0回答:1

我试图在 python 中使用 PLY 解析自定义编程语言,我有点困惑

所以例如,我想解析

on create:
  modifyProp relative width => 11
  modifyProp height => 14

我想让

on
部分像
def
一样工作,然后读取下一部分作为输入(在本例中为
create
,然后像在python中一样解析
:

我也想以同样的方式制作

modifyProp
部分,如果包含
relative
被读取为参数而不是输入,然后读取
=>
作为“将其更改为”命令,然后读取整数

抱歉,如果这有点令人困惑,我能找到的任何资源都太令人困惑了,我无法自己解决这个问题,如果您能提供帮助,请提前致谢

python python-3.x parsing lex ply
1个回答
0
投票

我们想要:

on create:
  modifyProp relative width => 11
  modifyProp height => 14

as

str
ing 并在 Python 中格式化:

some_code_in_string = '''
def create(relative):
    def modifyProp(relative):
        return True if relative[0] >= 11 and relative[1] >= 14 else False
    return modifyProp(relative)
print(create(relative))
'''

这样我们就可以

exec
ute
some_code_in_string

exec(some_code_in_string, {'relative': [15, 20]})

输出:

True

现在如果我们有

a
几行代码已经在
str
ing(你可能已经有一个文件),我们可以做这样的事情:

def pythonicize(some_string):
    some_new_string = ''
    func_end = some_string.find(':')
    func_start = True
    index = func_end
    while func_start:
        index -= 1
        if some_string[index:func_end].__contains__(' '):
            func_start = False
    func_start = index
    some_new_string += 'def'
    some_new_string += some_string[func_start:func_end]
    some_new_string += '(relative):'
    some_new_string += '\n'
    some_new_string += '...'
    return some_new_string

a = '''
on create:
  modifyProp relative width => 11
  modifyProp height => 14
'''
b = pythonicize(a)
print(b)

输出:

def create(relative):
...

我不是很熟悉 PLY 语言,我只是让你入门,所以你可以按照你认为合适的方式完成

pythonicize
函数的编写;您可能需要考虑许多边缘情况(我不熟悉)。

© www.soinside.com 2019 - 2024. All rights reserved.