简体   繁体   English

字符串必须包含多个单词

[英]String must contain multiple words

I'm new to Python and I have a question. 我是Python的新手,我有一个问题。

I am making a simple chatbot and I want it to give answers to questions and things like that. 我正在做一个简单的聊天机器人,我希望它可以回答诸如此类的问题。

Here is an example: 这是一个例子:

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()

For something more advanced I need it to check for 2 strings. 对于更高级的东西,我需要它检查2个字符串。

I tried some things like: 我尝试了一些类似的事情:

  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()

But that made "quitnow" . 但这使"quitnow"

I also tried to replace the + with an & but that gave me an error: 我也尝试用&替换+ ,但这给了我一个错误:

TypeError: unsupported operand type(s) for &: 'str' and 'str' TypeError:&不支持的操作数类型:“ str”和“ str”

Does anyone have a short code to do this? 有人有短代码可以做到这一点吗? I don't want 5+ sentences, I want to keep it as short as possible. 我不要5个以上的句子,我想让它尽可能短。

Use separate clauses to check if both "quit" and "now" are in the ChatCommand eg 使用单独的子句检查"quit""now"是否都在ChatCommand例如

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

Note that in Python, the logical and operator && is and , and & is the bitwise and . 请注意,在Python中, 逻辑&运算符 &&是and ,and &按位and

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

另外,作为样式,Python中通常将CamelCase保留给Class es。

Use all() : 使用all()

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

If you want to avoid matching quit within quite , you can use a regex: 如果你想避免匹配quitquite ,您可以使用正则表达式:

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

because the \\b word boundary anchors only match at the start and end of a word. 因为\\b 单词边界锚仅在单词的开头和结尾匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM