Sympy 破坏了 python 中的正则表达式?

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

我有代码:

import re
import math
#from sympy import * # breaks?
#x, y, z = symbols('x y z')
#init_printing(use_unicode=True)


def evaluate_expression(expr, variables):
    # Evaluate the expression using eval(), and provide the variables dictionary
    return eval(expr, variables)

def main():
    tools = """
<<<[eval("5"),a_x]>>>
<<<[eval("5+a_x"),ans]>>>
"""

    variables = {}
    lines = tools.strip().split("\n")

    for line in lines:
        # Extract the inner array using regular expression
        match = re.search(r'<<<\[(.*?),(\w+)\]>>>', line)
        if match:
            # Extract expression and variable name
            expr = match.group(1)
            var_name = match.group(2)

            # Evaluate expression
            value = evaluate_expression(expr, variables)

            # Update variables dictionary
            variables[var_name] = value

            # Check if 'ans' is defined
            if 'ans' in variables:
                print("ans =", variables['ans'])
                break

if __name__ == "__main__":
    main()

如果我不导入 sympy,它运行正常,但如果我导入 sympy,它就会中断,无论我如何命名变量,研究都不再存在。我没听懂?

python regex math sympy
1个回答
0
投票

sympy
re
class
,当您导入所有
*
时,您会隐藏
re
导入。首先导入
sympy
或仅导入您实际需要的内容。

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