使用Python-NLTK创建基本的硬编码聊天机器人
什么是聊天机器人
近年来,聊天机器人越来越受欢迎,用于自动化用户与软件平台之间的简单对话。聊天机器人可以响应用户输入并理解自然语言输入。Python-NLTK(自然语言处理工具包)是一个强大的库,可用于执行自然语言处理(NLP)任务。在本教程中,我们将使用Python-NLTK创建一个简单的硬编码聊天机器人。
聊天机器人创建的核心概念是什么
聊天机器人创建的核心概念包括:
- 自然语言处理(NLP) - 聊天机器人使用NLP来理解人类语言并解释用户的意图。NLP涉及到词汇分割、词性标注和命名实体识别等技术。
-
对话管理 - 对话管理负责管理对话的流程,并在对话的多个回合中保持上下文。
-
机器学习 - 机器学习用于训练聊天机器人识别数据中的模式、进行预测并随时间改进。聊天机器人开发中使用了监督学习、无监督学习和强化学习等技术。
-
API和集成 - 聊天机器人通常需要与外部服务和API集成,以提供信息或完成用户的任务。
-
用户体验(UX) - 用户体验对于聊天机器人至关重要,因为它们应该易于使用和直观。用户体验考虑包括设计对话流程、选择适当的回应类型以及向用户提供清晰和有用的反馈。
前提条件
在开始任务之前,您应该已经安装了以下内容:
推荐的设置列表:
- pip install pandas、matplotlib
-
您应该可以访问任何独立的集成开发环境,比如VS-Code、PyCharm、Atom或Sublime Text。
-
您还可以使用在线的Python编译器,比如Kaggle.com、Google Cloud平台或其他任何编译器。
-
更新的Python版本。在撰写本文时,我使用的是3.10.9版本。
-
熟悉使用Jupyter笔记本的使用。
-
具备虚拟环境的知识和应用将有益但不是必需的。
-
预计您对统计学和数学有很好的理解。
-
安装Python-NLTK(http://www.nltk.org/install.html)。
-
熟悉文本处理(分词、词形还原、词干提取)。
安装所需的库
首先,我们需要安装所需的库来开发聊天机器人。聊天机器人开发需要使用NLTK,Regex,random和string库。要安装这些库,我们可以使用pip命令。
!pip install nltk
!pip install regex
!pip install random
!pip install string
导入所需的库
在安装了必要的库之后,我们需要在Python笔记本中导入这些库。以下是导入这些库的代码。
import nltk
import re
import random
import string
from string import punctuation
数据预处理
一旦所需的包被安装和导入,我们需要预处理数据。预处理包括删除所有不必要的数据,将数据分词成句子,并删除停用词。停用词是在对话背景下具有很少或没有意义的最常见的单词,例如“a”,“is”等。
# Download stopwords from nltk
nltk.download('punkt')
nltk.download('stopwords')
stop_words = set(nltk.corpus.stopwords.words('english'))
def sentence_tokenizer(data):
# Function for Sentence Tokenization
return nltk.sent_tokenize(data.lower())
def word_tokenizer(data):
# Function for Word Tokenization
return nltk.word_tokenize(data.lower())
def remove_noise(word_tokens):
# Function to remove stop words and punctuation
cleaned_tokens = []
for token in word_tokens:
if token not in stop_words and token not in punctuation:
cleaned_tokens.append(token)
return cleaned_tokens
构建聊天机器人
既然我们已经对数据进行了预处理,我们就可以开始构建聊天机器人了。聊天机器人的流程可以用以下步骤总结:
- 定义模式和回复的列表
-
初始化一个无限循环
-
让用户输入一个查询
-
对查询进行分词并去除停用词
-
将查询与模式之一进行匹配并返回回复
# Define the Patterns and Responses
patterns = [
(r'hi|hello|hey', ['Hi there!', 'Hello!', 'Hey!']),
(r'bye|goodbye', ['Bye', 'Goodbye!']),
(r'(\w+)', ['Yes, go on', 'Tell me more', 'I’m listening...']),
(r'(\?)', ['I’m sorry, but I can’t answer that','Please ask me another question', 'I’m not sure what you mean.'])
]
# Function to generate response for the user input
def generate_response(user_input):
# Append User Input to chat history
conversation_history.append(user_input)
# Generate Random response
response = random.choice(responses)
return response
# Main loop of chatbot
conversation_history = []
responses = [response for pattern, response in patterns]
while True:
# User Input
user_input = input("You: ")
# End the Loop if the User Says Bye or Goodbye
if user_input.lower() in ['bye', 'goodbye']:
print('Chatbot: Goodbye!')
break
# Tokenize the User Input
user_input_tokenized = word_tokenizer(user_input)
# Remove Stop Words
user_input_nostops = remove_noise(user_input_tokenized)
# Process Query and Generate Response
chatbot_response = generate_response(user_input_nostops)
# Print Response
print('Chatbot:', chatbot_response)
最终代码
import nltk
import re
import random
import string
from string import punctuation
# Download stopwords from nltk
nltk.download('punkt')
nltk.download('stopwords')
stop_words = set(nltk.corpus.stopwords.words('english'))
def sentence_tokenizer(data):
# Function for Sentence Tokenization
return nltk.sent_tokenize(data.lower())
def word_tokenizer(data):
# Function for Word Tokenization
return nltk.word_tokenize(data.lower())
def remove_noise(word_tokens):
# Function to remove stop words and punctuation
cleaned_tokens = []
for token in word_tokens:
if token not in stop_words and token not in punctuation:
cleaned_tokens.append(token)
return cleaned_tokens
# Define the Patterns and Responses
patterns = [
(r'hi|hello|hey', ['Hi there!', 'Hello!', 'Hey!']),
(r'bye|goodbye', ['Bye', 'Goodbye!']),
(r'(\w+)', ['Yes, go on', 'Tell me more', 'I’m listening...']),
(r'(\?)', ['I’m sorry, but I can’t answer that', 'Please ask me another question', 'I’m not sure what you mean.'])
]
# Function to generate response for the user input
def generate_response(user_input):
# Append User Input to chat history
conversation_history.append(user_input)
# Generate Random response
response = random.choice(responses)
return response
# Main loop of chatbot
conversation_history = []
responses = [response for pattern, response in patterns]
while True:
# User Input
user_input = input("You: ")
# End the Loop if the User Says Bye or Goodbye
if user_input.lower() in ['bye', 'goodbye']:
print('Chatbot: Goodbye!')
break
# Tokenize the User Input
user_input_tokenized = word_tokenizer(user_input)
# Remove Stop Words
user_input_nostops = remove_noise(user_input_tokenized)
# Process Query and Generate Response
chatbot_response = generate_response(user_input_nostops)
# Print Response
print('Chatbot:', chatbot_response)
输出
在这个部分,我们可以看到代码的输出:
用户输入 −
用户需要输入一个字符串,就像是欢迎消息或问候语,聊天机器人将会相应作出回应。
根据回应,聊天机器人将创建回应
当用户在输入部分写入bye时,聊天机器人结束聊天。
结论
在本教程中,我们学习了如何使用Python-NLTK库创建一个简单的硬编码聊天机器人,并为每个子部分提供了示例。该聊天机器人可以根据用户输入回复预定义的回应。我们还学习了句子分词、词分词、去除停用词和模式匹配。这些技术将有助于构建更复杂的聊天机器人。