【问题标题】:How to turn a string expression into a normal expression in python [duplicate]如何在python中将字符串表达式转换为普通表达式[重复]
【发布时间】:2021-07-28 07:48:08
【问题描述】:

我只是想知道如何将字符串表达式转为普通表达式,在哪里可以解决。

例子:

"1 + 1"

我不希望上面的字符串出现,我希望它是

1 + 1

另一个例子:

"2(4 - 3) * 2"

我想把上面变成底部:

2(4 - 3) * 2

这样。那么有人可以让我知道该怎么做吗?谢谢!

请不要说使用eval,因为它可以解方程。我不想解决它,我希望它不在字符串中。

【问题讨论】:

  • 这能回答你的问题吗? Evaluating a mathematical expression in a string
  • 不要介意solve it 部分。我想要做的就是将字符串表达式变成一个正常的表达式,它应该不在字符串中
  • 这里似乎没有人知道您所说的“正常表达”是什么意思,包括我在内。也许您需要详细说明一下。例如。你打算用这个“正常表达”做什么? (意味着当它是一个字符串时可以打印它,解决/评估/执行它可以用eval 完成,还有一些更深奥的用例,但我无法想象这就是你要问的大约因为您的问题将包括语法树等单词。)

标签: python


【解决方案1】:

使用eval

>>>eval('1 + 1')
2

【讨论】:

  • 我没有使用eval,因为这是解决它,我要做的就是将表达式转换为普通表达式,而不是字符串。跨度>
【解决方案2】:

您可以使用eval("1 + 1") 将任何字符串计算为python 表达式。

"2(4 - 3) * 2" 不是一个有效的 python 表达式,所以你不能eval那个。

使用eval 时必须小心,但如果您传入任何用户提供的输入,因为它有效地允许他们执行任意代码字符串。

【讨论】:

  • 我没有尝试使用eval 或尝试解决它。我想要的只是将它从字符串中删除并使其成为正常表达式。不是字符串中的表达式。
【解决方案3】:

使用eval(str):

>>> eval('2 * (4 - 3) * 2')
4

如果您需要使用fordefimport 和其他使用exec(str)

【讨论】:

  • 执行您的示例会出错。如果用户不知道 eval 指令,他可能也不明白为什么 tis 会失败。你可以给出一些提示。
  • 在数学中 2(4 - 3) * 2 = 4 但在 python 中 SyntaxError 对于 py 2 * (4 - 3) * 2 是正确的
  • 不,我不是要解决这个问题,我是想让那个表达式成为一个普通的表达式,而不是一个字符串。
【解决方案4】:

Python 提供了几种方法来执行它自己的代码。通常有两个Built-in Functions可以让我们从python内部执行python代码-:

  • eval function -: eval 函数可用于执行您需要的任何表达式,但请注意,使用 eval 无法执行多行 python 代码。
  • exec function -: exec 函数也可用于动态执行多行 python 代码。因此,它不同于 eval 函数,因为它能够执行的不仅仅是 python 表达式。

现在对于您的用例,因为您只想执行存储在字符串中的 python 表达式,可以说e,可以执行以下操作 -:

e = '(2 *(4 - 3)) * 2' # Note that the previously written expression [2(4 - 3) * 2 is not a valid python expression as pointed out by @Brendan Abel]
result = eval(e) # The eval function executes the expression e and the result is stored in the result variable.

编辑:因此,在您发表评论后,您似乎需要将其转换为可供您使用并且可以随时运行的正常表达式。

同样,我们可以创建一个名为 Expression 的类,然后我们可以让它将表达式存储为 .py 文件。

该类的表达式对象可以随时运行,也可以在最后处理删除最初创建的.py文件。

相同的代码看起来像这样 -:

import importlib # Used for the Expression.run method.
import os # Used for the Expression.dispose method.

class Expression() :
    def __init__(self, expr_name, str_expr) :
        # This function is called at initialization of an Expression object.
        
        self.expr_name = expr_name
        self.str_expr = str_expr
        
        self.module_obj = None # To store the module object returned by the import_module function.(defaultly None)
        
        self.store() # Saves the expression as a .py file.
        return
    
    def store(self) :
        # Creates a .py file with the name as that of the expression name to store
        # the string expression for it to be later executed.
        
        addr = self.expr_name + '.py'
        with open(addr, 'w') as f :
            f.write(self.str_expr)
        return
    
    def dispose(self) :
        # Should be called either at the end of the program or whenever the use
        # for the expression has ended and no further use is needed, this function
        # deletes the .py file created initially to store the expression.
        
        addr = self.expr_name + '.py'
        os.remove(addr)
        return
    
    def run(self) :
        # This function can be called to execute the expression and it imports
        # the .py file previously created to indirectly execute it.
        
        if self.module_obj == None :
            # If the module_obj value is None it means the module is being
            # imported for the first time.
            self.module_obj = importlib.import_module(self.expr_name)
        else :
            # If the module_obj value is not None then the module has been
            # imported before and thus is now reloaded using the previously
            # stored module object.
            self.module_obj = importlib.reload(self.module_obj)
        return
    
    pass

# The string expression.
e = 'print((2 * (4 - 3)) * 2)'
# Creating an expression object.
e_ = Expression('e1', e)

# Will print the result three times
e_.run()
e_.run()
e_.run()

# Now we dispose the expression since it is not needed anymore.
e_.dispose()

同样的输出是-:

4
4
4

程序执行完毕后,如果使用的表达式已经被释放,所有使用的.py表达式文件都将被删除。

【讨论】:

  • 我不想使用evalexec 来解决它。我只想将字符串表达式转换为 不在字符串中的普通表达式。
  • 那么您可以使用 file i-o 写入文件并将表达式写入其中并以 .py 扩展名保存。然后就变成了正常的python表达式。
  • 也不是很清楚你想在哪里放置正常的表达式。
  • 如果与字符串表达式在同一位置,您可以再次将整个当前文件代码写入新的 .py 文件,并将字符串表达式替换为正常的。
  • 我的意思是这样的:我有一个字符串表达式。但是我想把它变成一个普通表达式,当我运行普通表达式时,它不应该是一个字符串。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-22
  • 2013-06-09
  • 1970-01-01
  • 2022-12-02
  • 1970-01-01
相关资源
最近更新 更多