5 分钟内构建您的第一个聊天机器人
我在网上搜索“如何构建聊天机器人?”,发现了ChatterBot,它是一款用于创建聊天机器人的机器学习对话引擎。
ChatterBot 的工作原理
在本文中,我们将了解如何在短短 5 分钟内使用 ChatterBot 构建聊天机器人。
让我们开始吧
pip install ChatterBot
创建文件chat.py
#import ChatBot
from chatterbot import ChatBot
创建一个新的聊天机器人,并命名为您选择的名称(我使用“Candice”)。
bot = ChatBot('Candice')
您的机器人已创建,但此时您的机器人还没有任何知识,为此您必须根据一些数据对其进行训练。Also, by default the ChatterBot library will create a sqlite database to build up statements of the chats.
训练你的机器人
#import ListTrainer
from chatterbot.trainers import ListTrainer
bot.set_trainer(ListTrainer)
# Training
bot.train(['What is your name?', 'My name is Candice'])
bot.train(['Who are you?', 'I am a bot, created by you' ])
你的机器人现在已经完成了 2 条语句的训练。当你问机器人“你叫什么名字”时,它会回答“我叫 Candice”。
您还可以对多个语句进行训练,例如
bot.train(['Do you know me?', 'Yes, you created me', 'No', 'Sahil?', 'No idea'])
正如你所见,训练机器人理解每一条语句非常困难。因此,我们将ChatterBotCorpusTrainer
在大型数据集上训练机器人。
from chatterbot.trainers import ChatterBotCorpusTrainer
# Create a new trainer for the chatbot
trainer = ChatterBotCorpusTrainer(bot)
# Train the chatbot based on the english corpus
trainer.train("chatterbot.corpus.english")
# Get a response to an input statement
chatbot.get_response("Hello, how are you today?")
或者您可以下载您的语言的数据集并用您的语言训练您的机器人。
我下载了英语数据集,我们可以像这样训练我们的机器人
for files in os.listdir('./english/'):
data=open('./english/'+files,'r').readlines()
bot.train(data)
NOTE: Make sure the dataset and the program file is on same folder, otherwise edit the path.
聊天功能
# To exit say "Bye"
while True:
# Input from user
message=input('\t\t\tYou:')
#if message is not "Bye"
if message.strip()!='Bye':
reply=bot.get_response(message)
print('Candice:',reply)
# if message is "Bye"
if message.strip()=='Bye':
print('Candice: Bye')
break
要运行它,请转到终端
python chat.py
它会先训练你的机器人,然后你就可以开始聊天。
源代码
#import libraries
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
import os
#Create a chatbot
bot=ChatBot('Candice')
bot.set_trainer(ListTrainer)
#training on english dataset
for files in os.listdir('./english/'):
data=open('./english/'+files,'r').readlines()
bot.train(data)
#chat feature
while True:
message=input('\t\t\tYou:')
if message.strip()!='Bye':
reply=bot.get_response(message)
print('Candice:',reply)
if message.strip()=='Bye':
print('Candice: Bye')
break