Python子句匹配代码异常:无关句子匹配却返回YES的问题排查
问题分析与解决方案
这不是字符串处理的问题,而是你对Python条件表达式的逻辑写法理解有误哦!
错误原因拆解
你的条件语句写法存在逻辑漏洞,我们把它拆解开来看:
# 你的代码等价于这个结构 if ("Rachel has made coffee to Joey and Chandler for the first time of her entire life.") or ("目标句子2" in sentence):
在Python中,任何非空字符串都会被视为布尔值True。你的第一个条件部分只是一个非空字符串,没有和sentence做包含判断,所以它本身就会被判定为True。而or逻辑只要有一个分支为True,整个表达式结果就是True,这就导致不管第二个条件是否成立,代码都会执行print("YES")。
修正后的代码
你需要给每个目标句子都加上in sentence的判断,确保两个条件都是“目标字符串是否在原句中”,再用or连接:
sentence = "While speaking to Ross, Rachel comes to terms with something that was bothering her." if "Rachel has made coffee to Joey and Chandler for the first time of her entire life." in sentence or "Monica can't stop smiling while having a conversation with Rachel." in sentence: print("YES") else: print("NO!")
运行这段修正后的代码,就会输出你预期的NO!了。
内容的提问来源于stack exchange,提问作者paulc1111
相关产品推荐
相关产品推荐

