【问题标题】:elif statement combined with "and" or "or" not workingelif 语句结合“and”或“or”不起作用
【发布时间】:2016-03-17 19:42:41
【问题描述】:

我正在为我的氏族编写这个电报机器人。机器人应该根据文本消息中的几个词发送回复。假设我在包含“Thalia”和“love”这两个词的组中输入了一个文本,并且我希望机器人做出响应。以下工作。

elif "thalia" in text.lower():
    if "love" in text.lower():
        reply("I love u too babe <3." "\nBut I love my maker even more ;).")
    else:
        reply("Say my name!")

msg containing thalia and love

我这样编码是因为当我使用“and”或“or”关键字时,语句不起作用,机器人会发疯。在上面,如果我编码:elif "thalia" and "love"..... 它不起作用。

如果有其他编码方式,我将不胜感激!

现在我正在用“and”和“or”对更多单词尝试相同的技术,但它不起作用。如果我离开“和”和“或”,它工作正常。但是当然,我不能在这个特定的响应中使用我想要的单词组合。

 elif "what" or "when" in text.lower():
    if "time" or "do" in text.lower():
        if "match" in text.lower():
            reply ("If you need assistence with matches, type or press /matches")

it triggered the command without the 3 words in one sentence

如何以更“专业”的方式重写此代码,我需要进行哪些更改才能使其正常工作?机器人只有在像 thalia love code 中那样使用单词组合时才会做出响应。而不是在使用“匹配”时。*

【问题讨论】:

  • if any(x in text.lower() for x in ('time', 'do')
  • 谢谢这对我有帮助 我感谢你的帮助 ????我很遗憾你不得不编辑我的帖子,下次会更加注意;)

标签: python-3.x if-statement telegram telegram-bot python-telegram-bot


【解决方案1】:

Python 很像自然语言,但解释器无法填充人类听众可以填充的内容。 'a and b in c' 必须写成 'a in c and b in c'。

在编写 if 语句之前,您应该将文本小写一次,而不是重复。然后把它变成一组单词,去掉标点和符号后,避免小写字符串的重复线性搜索。这是仅 ascii 输入的不完整示例。

d = str.maketrans('', '', '.,!')  # 3rd arg is chars to delete
text = set(text.lower().translate(d).split())

你的“匹配”sn-p 可以写成如下。

elif (("what" in text or "when" in text) and 
      ("time" in text or "do" in text) and
      "match" in text)
    reply ("If you need assistence with matches, type or press /matches")

你也可以使用正则表达式匹配来做同样的事情,但是像上面这样的逻辑语句可能更容易开始。

【讨论】:

  • 很好,这效果更好,我很感谢您的帮助先生!我想知道,如果我想在“时间”或“做”的同一行中添加“拥有”,代码将如何改变。因为我不确定你可以用“或”做三件事。这不行吗?:("time" in text or "do" in text or "have" in text ) 。那么它是如何工作的呢?
  • a or b or c 很好。易于尝试:&gt;&gt;&gt; False or False or True 将回显True
猜你喜欢
  • 2018-08-10
  • 2023-03-07
  • 1970-01-01
  • 2017-11-16
  • 1970-01-01
  • 1970-01-01
  • 2022-11-03
  • 2012-10-15
  • 2011-07-06
相关资源
最近更新 更多