目录
前言
使用的软件:Visual Studio Codehttps://code.visualstudio.com/
使用的语言:Python(3.10.10)
Python Release Python 3.10.10 | Python.orgThe official home of the Python Programming Languagehttps://www.python.org/downloads/release/python-31010/ 需要安装的库:chatterbot、nltk
准备流程
一、chatterbot库的安装
GitHub - gunthercox/ChatterBot: ChatterBot is a machine learning, conversational dialog engine for creating chat botshttps://github.com/gunthercox/ChatterBot 下载后解压,加压后在VS Code中打开文件夹并打开终端
在终端中先后运行以下指令()
python setup.py build
python setup.py install
pip install spacy
pip install chatterbot==1.0.4
二、nltk库的安装与必要文件下载
在终端中运行以下代码安装nltk库
pip install nltk
安装完成后,挂上VPN,运行以下python程序:
import nltk
nltk.download('averaged_perceptron_tagger')
nltk.download('punkt')
nltk.download('stopwords')
网络顺畅的话很快就可以下载完成。
以上是全部准备流程
主要程序
直接贴代码:
# 文件路径:C:\Users\since\Desktop\chatterbot\my_chatterbot.py
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
# import nltk
# 下载必要的NLTK数据
# nltk.download('averaged_perceptron_tagger')
# nltk.download('punkt')
# nltk.download('stopwords')
# 创建一个新的ChatBot实例
chatterbot = ChatBot("Training Example")
# 为chatbot创建一个新的训练器
trainer = ListTrainer(chatterbot)
# 根据提供的数据训练chatbot
trainer.train([
"Hi there!",
"Hello",
])
trainer.train([
"Greetings!",
"Hello",
])
# 启动与用户的交互
print('Hello! Type something to begin, or type "exit" to end the chat.')
while True:
user_input = input("You: ")
if user_input.lower() == 'exit':
print('Goodbye!')
break
else:
response = chatterbot.get_response(user_input)
print(f"Bot: {response}")
运行结果
代码解释
from chatterbot import ChatBot
导入ChatterBot库中的ChatBot类,用于创建聊天机器人实例。
from chatterbot.trainers import ListTrainer
导入ChatterBot库中的ListTrainer类,用于训练聊天机器人。
chatterbot = ChatBot("Training Example")
创建一个名为"Training Example"的ChatBot实例,这是聊天机器人的名称。
trainer = ListTrainer(chatterbot)
创建一个ListTrainer实例,该实例用于训练聊天机器人。
trainer.train([...])
使用ListTrainer训练聊天机器人,提供一组对话样本。在这个例子中,有两组对话样本,每组都包括一个用户输入和聊天机器人的回应。
print('Hello! Type something to begin, or type "exit" to end the chat.')
显示提示消息,提示用户可以开始与聊天机器人交互。
while True:
进入一个无限循环,聊天机器人将一直等待用户的输入,直到用户输入"exit"来结束聊天。
user_input = input("You: ")
等待用户输入,将用户输入存储在user_input
变量中。
if user_input.lower() == 'exit':
检查用户输入是否为"exit",如果是,跳出循环,结束聊天。
response = chatterbot.get_response(user_input)
如果用户没有输入"exit",则使用ChatterBot的get_response
方法获取聊天机器人的回应,根据用户的输入。
print(f"Bot: {response}")
打印聊天机器人的回应,以及"Bot: "前缀,以区分用户和机器人的消息。