Skip to main content
 首页 » 编程设计

python之使用正则表达式设置变量

2024年10月24日29jyk

我正在用正则表达式创建一种语言,这是我目前的代码:

    import re 
 
    outputf=r'output (.*)' 
    inputf=r'(.*) = input (.*)' 
    intf=r'int (.*) = (\d)' 
    floatf=r'float (.*) = (\d\.\d)' 
 
    def check_line(line): 
        outputq=re.match(outputf, line) 
        if outputq: 
            exec ("print (%s)" % outputq.group(1)) 
 
        inputq=re.match(inputf, line) 
        if inputq: 
            exec ("%s=raw_input(%s)"%(inputq.group(1), inputq.group(2))) 
 
        intq=re.match(intf, line) 
        if intq: 
            exec ("%s = %s"%(intq.group(1), intq.group(2))) 
            print x 
 
        floatq=re.match(floatf, line) 
        if floatq: 
            exec ("%s = %s"%(floatq.group(1), floatq.group(2))) 
 
 
    code=open("code.psu", "r").readlines() 
 
    for line in code: 
        check_line(line)  

所以效果很好,但在我的文件中,这是我的代码:

int x = 1 
output "hi" 
float y = 1.3 
output x 

但是当我读到第 4 行时,它说变量 x 没有定义。我如何设置它以便它也可以打印变量?

请您参考如下方法:

当调用 exec() 时,它可以选择性地传递它将使用的变量的全局和局部字典。默认情况下,它使用 globals() 和 locals()。

问题是,您在示例中使用 exec() 设置变量,如 x = 1。这确实设置好了,您可以在 locals() 中看到它。但是在你离开这个函数之后,那个变量就消失了。

因此,您需要在每次 exec() 调用后保存 locals()。

编辑:

我正在写这个附录,因为你自己回答了它,所以我想我还是把它贴出来了......

这是一个失败的简单示例(与您的示例相同的错误):

def locals_not_saved(firsttime): 
    if firsttime: 
        exec("x = 1") 
    else: 
        exec("print(x)") 
 
locals_not_saved(True) 
locals_not_saved(False) 

这是一个修改版本,通过将 locals() 保存为函数的属性来保存和重用它们 - 这只是一种方法,YMMV。

def locals_saved(firsttime): 
    if not hasattr(locals_saved, "locals"): 
        locals_saved.locals = locals() 
 
    if firsttime: 
        exec("x = 1", globals(), locals_saved.locals) 
    else: 
        exec("print(x)", globals(), locals_saved.locals) 
 
locals_saved(True) 
locals_saved(False)