I'm thinking we should create a simple and self-contained example instead of a huge framework. I'll consider using a dataset defined in JSON with intents, patterns, and responses. Training could involve scikit-learn for TF-IDF and LinearSVC, but I might also explore simpler options like rule-based pattern matching with spaCy or regex.
My goal is to present code that loads a small list of Q/A pairs and uses sklearn's TfidfVectorizer along with cosine similarity to retrieve the best response. This approach will create a straightforward retrieval-based chatbot. I plan to keep explanations short and provide a requirements snippet like "pip install nltk scikit-learn" to get started.Creating a simple chatbot script
I’m crafting a script to design a simple NLP-powered chatbot. First, I’ll import necessary modules and define a small knowledge base as a list of dictionaries for questions and answers. Next, I plan to preprocess the text by converting it to lowercase, removing punctuation, and potentially using NLTK's WordNetLemmatizer for lemmatization.
Then, I’ll create a TF-IDF model based on the questions. The chat loop will involve user input, preprocessing, transformation, and computing cosine similarities to pick the best response, implementing a fallback if the similarity doesn’t meet a threshold. I'll also consider adding an intent classification approach but I think keeping it straightforward is better.Building the chatbot code
I'm contemplating including an optional generative transformer using HuggingFace's "text-generation" with 'gpt2', but that can sometimes produce incoherent output. However, since the question focuses on providing Python code for a chatbot using NLP techniques, a retrieval model should do just fine.
I’ll include the necessary imports for sklearn and NLTK. I can use the TfidfVectorizer and cosine similarity from sklearn, and ensure to download NLTK stopwords, wordnet, and punkt safely. I also want to wrap everything in "if name == 'main':" with a chat loop for final code structure. Let’s get crafting! Below is a minimal but complete example of a terminal-based chatbot that uses NLP techniques (tokenization, lemmatization, TF‑IDF vectorization, cosine similarity) to pick the best response from a small knowledge base.
1. Install dependencies
bash
pip install nltk scikit-learn
2. Python code: chatbot.py
python
import string
import warnings
warnings.filterwarnings("ignore")
import nltk
from nltk.corpus import stopwords, wordnet
from nltk.stem import WordNetLemmatizer
from nltk import pos_tag, word_tokenize
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
# -------------------------------------------------------------------
# 1. One-time NLTK data download (only needed first run)
# -------------------------------------------------------------------
def setup_nltk():
try:
nltk.data.find("tokenizers/punkt")
nltk.data.find("corpora/wordnet")
nltk.data.find("corpora/stopwords")
nltk.data.find("taggers/averaged_perceptron_tagger")
except LookupError:
nltk.download("punkt")
nltk.download("wordnet")
nltk.download("stopwords")
nltk.download("averaged_perceptron_tagger")
setup_nltk()
# -------------------------------------------------------------------
# 2. Sample knowledge base
# In a real project, you’d load this from a file or database.
# -------------------------------------------------------------------
knowledge_base = [
{
"question": "hello",
"answer": "Hi there! How can I help you today?"
},
{
"question": "hi",
"answer": "Hello! What can I do for you?"
},
{
"question": "how are you",
"answer": "I'm just code, but I'm running smoothly. How are you?"
},
{
"question": "what is your name",
"answer": "I'm a simple NLP-powered chatbot written in Python."
},
{
"question": "what can you do",
"answer": "I can answer basic questions from my small knowledge base and demonstrate NLP techniques."
},
{
"question": "how does tf idf work",
"answer": "TF-IDF measures how important a word is to a document in a collection, by combining term frequency and inverse document frequency."
},
{
"question": "what is natural language processing",
"answer": "Natural Language Processing (NLP) is a field of AI focused on enabling computers to understand and generate human language."
},
{
"question": "bye",
"answer": "Goodbye! It was nice talking with you."
}
]
# -------------------------------------------------------------------
# 3. Text preprocessing utilities
# -------------------------------------------------------------------
lemmatizer = WordNetLemmatizer()
stop_words = set(stopwords.words("english"))
punct_table = str.maketrans("", "", string.punctuation)
def get_wordnet_pos(treebank_tag):
"""Map POS tag to first character lemmatize() accepts."""
if treebank_tag.startswith("J"):
return wordnet.ADJ
elif treebank_tag.startswith("V"):
return wordnet.VERB
elif treebank_tag.startswith("N"):
return wordnet.NOUN
elif treebank_tag.startswith("R"):
return wordnet.ADV
else:
return wordnet.NOUN # default
def preprocess(text: str) -> str:
"""
Lowercase, remove punctuation, tokenize, POS-tag, lemmatize,
and remove stopwords. Returns a cleaned string.
"""
# Lowercase and remove punctuation
text = text.lower().translate(punct_table)
# Tokenize
tokens = word_tokenize(text)
# Remove stopwords
tokens = [t for t in tokens if t not in stop_words]
# POS tagging
tagged = pos_tag(tokens)
# Lemmatize with POS
lemmas = [
lemmatizer.lemmatize(word, get_wordnet_pos(tag))
for word, tag in tagged
]
return " ".join(lemmas)
# -------------------------------------------------------------------
# 4. Fit a TF-IDF model on the knowledge base questions
# -------------------------------------------------------------------
questions = [item["question"] for item in knowledge_base]
vectorizer = TfidfVectorizer(
preprocessor=preprocess, # our custom preprocessor
tokenizer=lambda x: x.split(), # already tokenized by preprocess
ngram_range=(1, 2), # unigrams + bigrams
)
tfidf_matrix = vectorizer.fit_transform(questions)
# -------------------------------------------------------------------
# 5. Matching user input to the best answer
# -------------------------------------------------------------------
def find_best_answer(user_input: str, threshold: float = 0.2) -> str:
"""
Convert user input to TF-IDF vector, compute cosine similarity
with all knowledge base questions, and return the best answer
if similarity is above a threshold; otherwise a fallback message.
"""
if not user_input.strip():
return "Please type something so I can respond."
user_vec = vectorizer.transform([user_input])
similarities = cosine_similarity(user_vec, tfidf_matrix).flatten()
best_index = similarities.argmax()
best_score = similarities[best_index]
if best_score < threshold:
return (
"I'm not sure I understand that yet. "
"Could you rephrase or ask something else?"
)
return knowledge_base[best_index]["answer"]
# -------------------------------------------------------------------
# 6. Chat loop
# -------------------------------------------------------------------
def chat():
print("NLP Chatbot (type 'quit', 'exit', or 'bye' to stop)")
while True:
user_input = input("You: ").strip()
if user_input.lower() in {"quit", "exit", "bye"}:
print("Bot: Goodbye! 👋")
break
response = find_best_answer(user_input)
print("Bot:", response)
if __name__ == "__main__":
chat()