如何在Python中为聊天机器人创建对话?

时间:2018-09-05 09:59:18

标签: python chatbot

我想写一个可以与用户对话的快速简单的聊天机器人。我想知道如何创建允许无限数量的输入响应的对话框。现在,我正在使用的代码不允许用户定义的输入。这是我现在正在使用的代码。

# Import the random module
import random

bot_template = "AGENT: {0}"
user_template = "USER: {0}"

# Define variables
name = "Greg"
weather = "cloudy"

# Define a dictionary containing a list of responses for each message
responses = {
  "what's your name?": [
      "my name is {0}".format(name),
      "they call me {0}".format(name),
      "I go by {0}".format(name)
   ],
  "what's today's weather?": [
      "the weather is {0}".format(weather),
      "it's {0} today".format(weather)
    ],
  "default": ["default message"]
}

# Use random.choice() to choose a matching response
def respond(message):
    # Check if the message is in the responses
    if message in responses:
        # Return a random matching response
        bot_message = random.choice(responses[message])
    else:
        # Return a random "default" response
        bot_message = random.choice(responses["default"])
    return bot_message

# Define a function that sends a message to the bot: send_message
def send_message(message):
    # Print user_template including the user_message
    print(user_template.format(message))
    # Get the bot's response to the message
    response = respond(message)
    # Print the bot template including the bot's response.
    print(bot_template.format(response))

# Send a message to the bot
send_message("what's today's weather?")

2 个答案:

答案 0 :(得分:2)

代替:

# Send a message to the bot
send_message("what's today's weather?")

您可以写:

while True:
    print('Write your message to the bot and press ENTER')
    user_msg = input()

    # Send a message to the bot
    send_message(user_msg)

这会将用户输入的消息发送到机器人,直到您停止程序为止。

答案 1 :(得分:0)

使用input()命令可以获取用户定义的字符串。它返回一个字符串,其中包含用户在运行该程序的shell中键入的行。