首页 > 解决方案 > 尝试构建逻辑解析器时出错

问题描述

所以我将这些字符串存储在数据库中,我想将它们转换为 python 表达式以将它们与 if 语句一起使用。我会将这些字符串存储到列表中并循环遍历它们。例如:

string = "#apple and @banana or @grapes"

我可以通过将#替换为“a==”和@替换为“b==”来转换此字符串:

if a == apple and b == banana or b == grapes

hash 指的是 a @ 指的是 b

但是当我使用 eval 时,它会抛出错误“未定义苹果”,因为苹果不在引号中。所以我想要的是这个:

if a == "apple" and b == "banana" or b == "grapes"

我有什么办法可以做到这一点?存储在 DB 中的字符串可以有任何类型的格式,可以有多个和/或条件。

几个例子:

string[0] = "#apple and @banana or @grapes"
string[1] = "#apple or @banana and @grapes"
string[2] = "#apple and @banana and @grapes"

将有其他条件没有满足条件

谢谢

标签: pythonpython-3.xdictionary

解决方案


我不确定你在这里问什么,但你可以使用replaceandsplit函数:

string = "#apple and #banana"
fruits = string.replace("#", "").split("and")
if a == fruits[0] and b == fruits[1]:

希望这可以帮助


推荐阅读