字符串必须包含多个单词

2024-04-28 19:29:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python的新手,我有一个问题。你知道吗

我正在做一个简单的聊天机器人,我希望它能回答问题和类似的事情。你知道吗

举个例子:

def ChatMode():
    ChatCommand = raw_input ("- user: ")
    if "quit" in ChatCommand :
        print "Lucy: See you later."
        print ""
        UserCommand()
    else :
        print "Lucy: sorry i don\'t know what you mean."
        ChatMode()

更先进的东西,我需要它来检查2字符串。你知道吗

我试过这样的方法:

  def ChatMode() :
      ChatCommand = raw_input ("- user: ")
      if "quit" + "now" in ChatCommand :
          print "Lucy: See you later."
          print ""
          UserCommand()
      else :
          print "Lucy: sorry i don\'t know what you mean."
          ChatMode()

但这使得"quitnow"。你知道吗

我还试图用&替换+,但这给了我一个错误:

TypeError: unsupported operand type(s) for &: 'str' and 'str'

有人有短代码来做这个吗?我不想要5个以上的句子,我想让它尽可能短。你知道吗


Tags: inyouinputrawifdefquitprint
3条回答
if "quit" in ChatCommand and "now" in ChatCommand:

另外,作为一种风格,在Python中CamelCase通常是为Class保留的。你知道吗

使用all()

if all(word in ChatCommand for word in ("quit", "now")):

如果要避免在quite内匹配quit,可以使用正则表达式:

import re
if all(re.search(regex, ChatCommand) for regex in (r"\bquit\b", r"\bnow\b")):

因为\bword boundary anchors只在单词的开头和结尾匹配。你知道吗

使用单独的子句检查"quit""now"是否都在ChatCommand中,例如

if "quit" in ChatCommand and "now" in ChatCommand:

注意,在Python中,logical and operator&;是and&bitwise and。你知道吗

相关问题 更多 >