The user wants a Python program that simulates a chatbot with natural language processing (NLP) using the spaCy library.
Key Requirements:
- Language: Python.
- Library:
spaCy (for NLP).
- Functionality: Simulate a chatbot (take input, process it, generate a response).
Steps to implement:
- Prerequisites: The user needs to install
spacy and download a language model (usually en_core_web_sm).
- Setup: Import
spacy and load the model.
- NLP Logic:
- How will the chatbot decide what to say? A hard-coded rules-based system is the standard approach for a simple demonstration without external AI APIs.
- Use
spaCy features:
- Tokenization/Lemmatization: Normalize input (e.g., "running" -> "run").
- Part-of-Speech (POS) Tagging: Identify nouns, verbs, etc. (maybe useful for context).
- Similarity: Use vector similarity (if using a model with vectors like
en_core_web_md or lg, but sm is faster/smaller and usually sufficient for basic keyword matching, though similarity scores are less accurate in sm). Decision: Stick to keyword/lemma matching for reliability in a basic script, or use similarity if I suggest a larger model. Let's go with a hybrid: Rule-based matching using lemmas is robust.
- Conversation Loop: A
while True loop to keep the chat going until the user says "bye".
- Structure of the Code:
- Import statements.
- Load NLP model.
- Define a function to process input.
- Define intents/responses (a dictionary mapping patterns to answers).
- Main loop.
Refining the NLP Logic (The "Smart" part):
To make it actually use spaCy rather than just simple string matching:
- Lemmatization: Instead of checking
if "running" in text, check if "run" in lemmas. This handles "run", "running", "ran".
- Entity Recognition: Maybe recognize names (PERSON) or places (GPE) to make the bot seem smarter (e.g., "I see you mentioned [Name]").
Drafting the Response Logic:
- Intent: Greeting
- Keywords (lemmas): hello, hi, hey.
- Response: "Hello there!"
- Intent: Name
- Keywords: name, call.
- Entity check: Look for a PERSON entity.
- Response: "Nice to meet you, [Name]." or "What is your name?"
- Intent: Feeling
- Keywords: feel, be (is/am/are).
- Response: "I am just a computer program."
- Intent: Exit
- Keywords: bye, quit, exit.
Code Skeleton:
import spacy
# Load model
nlp = spacy.load("en_core_web_sm")
# Data
responses = {
"greeting": ["Hi there!", "Hello!", "Hey!"],
"weather": ["I can't check the weather, but I hope it's nice!", "It's always sunny in code-land."],
"farewell": ["Goodbye!", "See you later!", "Have a nice day!"]
}
def chat(input_text):
doc = nlp(input_text)
# 1. Lemmatization for keyword matching
lemmas = [token.lemma_.lower() for token in doc]
# 2. Logic
if "hello" in lemmas or "hi" in lemmas:
return random.choice(responses["greeting"])
# ... more logic ...
else:
return "I didn't understand that."
Adding "Similarity" (Optional but cool):
Using doc.similarity() requires word vectors. en_core_web_sm doesn't have real word vectors (context-sensitive tensors only), so similarity might be unreliable or requires md or lg model. To keep the script runnable for beginners, I will focus on Pattern Matching (Matcher) or Lemmas rather than vector similarity, as it's more deterministic for a tutorial script. I will use the Matcher class as it's a very "spaCy" way of doing things.
Revised Plan with Matcher:
- Initialize
Matcher.
- Add patterns for specific intents (e.g.,
[{"LEMMA": "be"}, {"LOWER": "weather"}]).
- Process user input.
- Match against patterns.
- If no pattern matches, check for entities or fallback.
Let's stick to a robust "Bag of Lemmas" approach + Entity Extraction. It's easier to read and demonstrates the core NLP features (Tokenization, Lemmatization, NER) without overwhelming the user with Matcher syntax complexity unless necessary.
Features to highlight in the code:
- Lemmatization: Handles "ran" vs "run".
- Named Entity Recognition (NER): Detects names or organizations.
- Sentence Similarity: Just a simple check to show how it works (using
sm model, though rough).
Dependencies:
spacy
en_core_web_sm (download command provided)
Code Structure:
- Imports.
ChatBot class.
__init__: Load model.
process_input: The core logic.
run: The REPL loop.
Let's refine the logic inside process_input.
- Check for specific trigger words (lemmas).
- Check for "who/what/where" questions.
- Check for entities.
Let's write the actual code.
Self-Correction during drafting: Using doc.similarity with en_core_web_sm produces a warning saying it may not be useful. I will add a comment about this but use simple lemmas for the main logic to ensure the code works well out-of-the-box.
Final Code Layout:
- Install instructions (comments).
- Import
spacy and random.
- Load
en_core_web_sm.
- Define response rules (dictionaries).
- Loop:
- User input.
doc = nlp(input).
- Extract lemmas and entities.
- Priority 1: Exit commands.
- Priority 2: Greetings.
- Priority 3: Questions (NLP analysis).
- Priority 4: Entity detection (Smart response).
- Priority 5: Default fallback.
Let's make it slightly smarter by allowing the bot to remember the user's name if an entity is detected.
Steps for the user:
- Install spacy.
- Download model.
- Run script.
This seems solid. I will write the Python script now.
Here is a complete, functional Python program that creates a chatbot using the spaCy NLP library.
This bot uses Lemmatization (to understand that "running" and "ran" are the same concept), Named Entity Recognition (to identify names and places), and Similarity (to handle vague inputs).
Prerequisites
You will need to install spaCy and download the English language model.
- Install spaCy:
pip install spacy
- Download the language model:
python -m spacy download en_core_web_sm
The Python Program
Save this code in a file named nlp_bot.py and run it.
import spacy
import random
import sys
# 1. Load the spaCy NLP model
# This model allows us to tokenize, lemmatize, and find entities
print("Loading spaCy model...")
try:
nlp = spacy.load("en_core_web_sm")
except OSError:
print("Error: Model 'en_core_web_sm' not found.")
print("Please run this command in your terminal: python -m spacy download en_core_web_sm")
sys.exit()
# 2. Define the Chatbot Logic
class NLPChatbot:
def __init__(self):
self.user_name = None
# Define patterns: We map intents to lists of lemmatized keywords
self.intents = {
"greeting": ["hello", "hi", "hey", "greetings"],
"goodbye": ["bye", "goodbye", "see", "later", "quit", "exit"],
"thanks": ["thank", "thanks", "appreciate"],
"capacity": ["do", "can", "help", "ability"],
"mood": ["how", "are", "you", "feeling", "doing"],
"weather": ["weather", "temperature", "rain", "sunny"]
}
# Define responses for each intent
self.responses = {
"greeting": ["Hello!", "Hi there!", "Greetings! How can I help?"],
"goodbye": ["Goodbye!", "See you later!", "Have a nice day!"],
"thanks": ["You're welcome!", "Happy to help.", "No problem!"],
"capacity": ["I am a bot built with spaCy. I can understand grammar and entities.",
"I can identify Names, Places, and Organizations in your text."],
"mood": ["I am just code, so I don't have feelings, but I'm running smoothly!", "I feel fantastic!"],
"weather": ["I don't have access to live data, but I hope it's sunny!", "Check your window!"],
"identity": ["I am your spaCy NLP Assistant."],
"fallback": ["I'm not sure I understand. Could you rephrase?",
"Interesting. Tell me more.",
"I process language, but that sentence confuses me."]
}
def process_input(self, text):
"""
Uses spaCy to process user input, extract entities, and determine intent.
"""
# Pass text through the pipeline
doc = nlp(text)
# --- Feature 1: Named Entity Recognition (NER) ---
# If the user mentions a Person or Organization (like a name), capture it.
for ent in doc.ents:
if ent.label_ == "PERSON":
self.user_name = ent.text
return f"Nice to meet you, {ent.text}!"
# --- Feature 2: Intent Matching via Lemmatization ---
# Convert the sentence into a clean set of base words (lemmas)
# e.g., "I am running" -> ["be", "run"]
lemmas = [token.lemma_.lower() for token in doc if not token.is_stop and not token.is_punct]
# Check against our known intents
for intent, keywords in self.intents.items():
# If there is an overlap between the user's lemmas and our keywords
if set(lemmas) & set(keywords):
return random.choice(self.responses[intent])
# --- Feature 3: Syntactic Dependency Parsing (Advanced) ---
# Example: Check if user asked "Who are you?"
if "who" in [t.text.lower() for t in doc] and "be" in lemmas:
return random.choice(self.responses["identity"])
# --- Fallback ---
# If no specific rules matched, check if the input is similar to a greeting
# using vector similarity (requires 'en_core_web_md' or 'lg' for better accuracy)
if doc.similarity(nlp("hello hi hey")) > 0.7:
return random.choice(self.responses["greeting"])
return random.choice(self.responses["fallback"])
# 3. Main Loop
def start_chat():
bot = NLPChatbot()
print("\n--- Bot is ready! Type 'quit' or 'bye' to exit. ---")
print("Tip: Try introducing yourself (e.g., 'My name is Alice') or ask about the weather.\n")
while True:
user_input = input("You: ")
if not user_input.strip():
continue
response = bot.process_input(user_input)
print(f"Bot: {response}")
# Check for exit condition
if any(word in user_input.lower() for word in ["bye", "quit", "exit"]):
break
if __name__ == "__main__":
start_chat()
How it works
-
Tokenization & Lemmatization:
- The bot breaks your sentences into words (tokens).
- It converts words to their "root" form (lemmas). For example, if you type "I ran to the store", the bot sees the lemma "run". This allows it to match keywords regardless of verb tense or plurality.
- It filters out Stop Words (common words like "the", "is", "at") to focus on the meaning.
-
Named Entity Recognition (NER):
- If you type "My name is Alice", spaCy identifies "Alice" as a
PERSON entity. The bot captures this and uses it in the response.
-
Intent Matching:
- The bot looks for overlap between your lemmas and a pre-defined dictionary of keywords. If you use words like "rain" or "sunny", it triggers the "weather" response.
-
Clean Exit:
- If you type "quit", "bye", or "exit", the loop breaks and the program ends.