使用Python构建一个简单的聊天机器人
发布时间:2023-12-26 21:18:48
Sure! Here's an example of building a simple chatbot using Python:
# Required Libraries
import nltk
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics.pairwise import cosine_similarity
# Initialize the chatbot
def initialize_chatbot():
# Preparing the data
nltk.download('punkt') # Download necessary nltk data
chat_history = [
'Hi',
'Hello',
'How are you?',
'I am good. How about you?',
'I am also doing well',
'That's great to hear',
'Thank you!'
]
# Prepare the corpus
corpus = nltk.sent_tokenize("
".join(chat_history))
# Initialize the CountVectorizer object and transform the corpus
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(corpus).toarray()
return X, corpus
# Generate a response from the chatbot
def generate_response(user_input, X, corpus):
# Preprocessing the user input
user_input = user_input.lower()
sentences = nltk.sent_tokenize(user_input)
# Transforming the user input using the CountVectorizer object
input_vector = vectorizer.transform(sentences).toarray()
# Finding the most similar sentence from the corpus
similarity_scores = cosine_similarity(X, input_vector)
most_similar_sentence_index = np.argmax(similarity_scores)
return corpus[most_similar_sentence_index]
# Main function to run the chatbot
def chatbot():
print("Chatbot: Hi! How can I assist you today?")
X, corpus = initialize_chatbot()
while True:
user_input = input("User: ")
if user_input.lower() == 'quit':
print("Chatbot: Bye! Have a nice day.")
break
response = generate_response(user_input, X, corpus)
print("Chatbot:", response)
# Run the chatbot
chatbot()
The above code initializes a simple chatbot that responds to user input based on pre-defined chat history. The initialize_chatbot function prepares the chat history as well as the corpus needed for calculating similarity scores. The responses are generated using the generate_response function, which finds the most similar sentence from the corpus based on cosine similarity.
To run the chatbot, you can simply call the chatbot function. The chatbot will greet the user and ask for input. It will continue responding to user input until the user enters 'quit'. The chatbot will then say goodbye and end the conversation.
Here's how a conversation with the chatbot might look like:
Chatbot: Hi! How can I assist you today? User: How are you? Chatbot: I am good. How about you? User: I am not doing well Chatbot: I am also doing well User: That's great to hear Chatbot: Thank you! User: Quit Chatbot: Bye! Have a nice day.
