如何使用PyPred编写符合语法的Python逻辑判断代码?
PyPred代码修正说明
问题点分析
- 原需求是精确匹配
message等于"How to catch taxi",但你用了contains,不符合预期逻辑; - PyPred的
Predicate需要结合变量值完成评估,仅传入表达式字符串无法生效; - 原逻辑中的
country和city被合并为place参数,若该参数确实可代表国家或城市,逻辑方向没问题,但需对齐PyPred语法规范。
修正后的代码
from pypred import Predicate def taxi_response(place, message): # 编写符合PyPred语法的表达式,精确匹配条件 expr = "(place == 'Russia' or place == 'Moscow') and message == 'How to catch taxi'" pred = Predicate(expr) # 传入变量上下文,评估表达式是否成立 if pred.test({"place": place, "message": message}): return "You can catch taxi here: link"
可选调整(若需区分country和city参数)
如果要严格对应原逻辑中的country和city两个独立参数,代码需调整为:
from pypred import Predicate def taxi_response(country, city, message): expr = "(country == 'Russia' or city == 'Moscow') and message == 'How to catch taxi'" pred = Predicate(expr) if pred.test({"country": country, "city": city, "message": message}): return "You can catch taxi here: link"
内容的提问来源于stack exchange,提问作者Роман Свирид
相关产品推荐
相关产品推荐

