python - 尝试构建逻辑解析器时出错
问题描述
所以我将这些字符串存储在数据库中,我想将它们转换为 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"
将有其他条件没有满足条件
谢谢
解决方案
我不确定你在这里问什么,但你可以使用replace
andsplit
函数:
string = "#apple and #banana"
fruits = string.replace("#", "").split("and")
if a == fruits[0] and b == fruits[1]:
希望这可以帮助
推荐阅读
- jquery - 在行悬停时展开 TH 元素
- c# - 邀请用户加入 Azure 应用需要哪些角色和权限?
- laravel - RelationShip Eloquent hasOne
- c++ - CGAL 绘图功能在 Visual Studio 中给出“CGAL_USE_BASIC_VIEWER 未定义”错误
- xml - 从特定父节点复制子节点并更改子节点的值
- matlab - Matlab:缺少间隔值的误差线图
- ansible - 在ansible-playbook中运行一个任务时如何切换或成为另一个远程用户?
- microsoft-graph-api - 从 MS Graph API 获取消息时出现错误 504,网关超时
- java - 为读取姓名、年龄和身高的 Java 赋值而苦苦挣扎
- css - React App 的不同组件中是否可以有多个整页背景图像?