Programmers PicnicAI-ML Classes by Champak Roy

NLP 61% to 70% • Make Your Own Chatbot

Build a Meaning-Based Chatbot using NLTK WordNet

Students now convert the WordNet meaning-matching idea into a working chatbot. The chatbot compares user input with stored intents, calculates meaning scores, selects the closest intent, and replies with confidence.

NLTKWordNetIntentMeaning scoreConfidenceChatbot

0 to infinity path

61% to 70% Roadmap

61%What is a chatbot?
62%What is an intent?
63%Why exact matching fails in chatbots
64%Meaning-based intent matching
65%Using WordNet synonym expansion
66%Comparing user input with many intents
67%Selecting the best reply
68%Adding confidence score
69%Mini project: Food or Movie chatbot
70%Mini project: Multi-intent chatbot

61%

What is a chatbot?

Simple meaning

A chatbot is a program that receives a user sentence and gives a useful reply. It may answer questions, guide the user, recommend something, or open a service.

User → Bot → Reply

Our chatbot type

Our chatbot is a meaning-based intent chatbot. It compares the user sentence with known examples and chooses the closest reply.

This is a good first chatbot before moving to transformer-based AI chatbots.

62%

What is an intent?

An intent is the purpose behind the user’s sentence. The user may use many different words, but the purpose may be the same.

User sentencePossible intentBot reply
I am hungryfoodYou may want something to eat.
I want to watch cinemamovieYou may want to watch a movie.
Teach me programmingstudyYou may want to open a learning lesson.
I am confusedhelpI can help you step by step.

63% and 64%

Why exact matching fails

User saysI am hungry
Stored intentI want food
Bot should inferFood intent

Exact matching may fail because hungry and food are not the same word. Meaning-based matching gives us a better beginner chatbot.

Setup

Install and download NLTK WordNet

Install NLTK

pip install nltk

Download WordNet data once

import nltk

nltk.download("wordnet")
nltk.download("omw-1.4")

65% and 69%

Start with your chatbot template

This first chatbot compares the user sentence with two stored meanings: I want food and I want films. The higher score wins.

Food or Movie Chatbot

from nltk.corpus import wordnet as wn
import re


def clean_words(sentence):
    sentence = sentence.lower()
    return re.findall(r"[a-z]+", sentence)


def synonyms_of(word):
    words = {word}

    for synset in wn.synsets(word):
        for lemma in synset.lemmas():
            words.add(lemma.name().lower().replace("_", " "))

    return words


def expanded_sentence_words(sentence):
    result = set()

    for word in clean_words(sentence):
        result.update(synonyms_of(word))

    return result


def sentence_meaning_score(sentence1, sentence2):
    words1 = expanded_sentence_words(sentence1)
    words2 = expanded_sentence_words(sentence2)

    common = words1.intersection(words2)
    total = words1.union(words2)

    if not total:
        return 0, common

    score = len(common) / len(total)
    return score, common


food_intent = "I want food"
movie_intent = "I want films"

for i in range(5):
    user_sentence = input("\nEnter a sentence:\n").lower().strip()

    food_score, food_common = sentence_meaning_score(food_intent, user_sentence)
    movie_score, movie_common = sentence_meaning_score(movie_intent, user_sentence)

    print("\nFood score:", round(food_score, 3))
    print("Movie score:", round(movie_score, 3))

    if food_score < movie_score:
        print("Bot: You may want to watch a movie.")
    else:
        print("Bot: You may want something to eat.")
Checkpoint: Run this program and type I am hungry, I want cinema, show me films, and I need snacks.

66% to 68%

A better chatbot structure

The first chatbot works, but it is difficult to add many topics. A better chatbot keeps all intents in a list. Each intent has a name, example sentence, and reply.

Cleaner intent-based chatbot

from nltk.corpus import wordnet as wn
import re


def clean_words(sentence):
    sentence = sentence.lower()
    return re.findall(r"[a-z]+", sentence)


def synonyms_of(word):
    words = {word}

    for synset in wn.synsets(word):
        for lemma in synset.lemmas():
            words.add(lemma.name().lower().replace("_", " "))

    return words


def expanded_sentence_words(sentence):
    result = set()

    for word in clean_words(sentence):
        result.update(synonyms_of(word))

    return result


def sentence_meaning_score(sentence1, sentence2):
    words1 = expanded_sentence_words(sentence1)
    words2 = expanded_sentence_words(sentence2)

    common = words1.intersection(words2)
    total = words1.union(words2)

    if not total:
        return 0, common

    score = len(common) / len(total)
    return score, common


intents = [
    {"name": "food", "example": "I want food", "reply": "You may want something to eat."},
    {"name": "movie", "example": "I want films", "reply": "You may want to watch a movie."},
    {"name": "study", "example": "I want to learn Python", "reply": "You may want to study a Python lesson."},
    {"name": "sleep", "example": "I want to rest", "reply": "You may need some rest."}
]


def chatbot_reply(user_sentence):
    best_intent = None
    best_score = -1
    best_common_words = set()

    for intent in intents:
        score, common_words = sentence_meaning_score(intent["example"], user_sentence)

        if score > best_score:
            best_score = score
            best_intent = intent
            best_common_words = common_words

    return best_intent, best_score, best_common_words


for i in range(5):
    user_sentence = input("\nYou: ").strip()
    intent, score, common_words = chatbot_reply(user_sentence)

    print("\nDetected intent:", intent["name"])
    print("Confidence score:", round(score, 3))
    print("Common meaning words:", common_words)
    print("Bot:", intent["reply"])

Visual model

How the chatbot thinks

1User sentence
2Clean words
3Expand synonyms
4Compare intents
5Select best score
6Reply

70% Final Project

Multi-Intent Meaning Chatbot

This is the full project for the 70% checkpoint. Each intent has many example sentences. The chatbot compares the user’s sentence with every example and chooses the best intent.

Final chatbot code

from nltk.corpus import wordnet as wn
import re


def clean_words(sentence):
    sentence = sentence.lower()
    return re.findall(r"[a-z]+", sentence)


def synonyms_of(word):
    words = {word}

    for synset in wn.synsets(word):
        for lemma in synset.lemmas():
            words.add(lemma.name().lower().replace("_", " "))

    return words


def expanded_sentence_words(sentence):
    result = set()

    for word in clean_words(sentence):
        result.update(synonyms_of(word))

    return result


def sentence_meaning_score(sentence1, sentence2):
    words1 = expanded_sentence_words(sentence1)
    words2 = expanded_sentence_words(sentence2)

    common = words1.intersection(words2)
    total = words1.union(words2)

    if not total:
        return 0, common

    score = len(common) / len(total)
    return score, common


intents = [
    {
        "name": "food",
        "examples": ["I want food", "I am hungry", "I want to eat", "Give me snacks"],
        "reply": "You may want something to eat."
    },
    {
        "name": "movie",
        "examples": ["I want films", "I want to watch a movie", "Show me cinema", "I want entertainment"],
        "reply": "You may want to watch a movie."
    },
    {
        "name": "study",
        "examples": ["I want to learn Python", "Teach me programming", "I want to study AI", "Show me a lesson"],
        "reply": "You may want to open a learning lesson."
    },
    {
        "name": "help",
        "examples": ["I need help", "Please support me", "I am confused", "Guide me"],
        "reply": "I can help you step by step."
    }
]


def score_intent(intent, user_sentence):
    best_score = 0
    best_common_words = set()
    best_example = ""

    for example in intent["examples"]:
        score, common_words = sentence_meaning_score(example, user_sentence)

        if score > best_score:
            best_score = score
            best_common_words = common_words
            best_example = example

    return best_score, best_common_words, best_example


def chatbot_reply(user_sentence):
    best_intent = None
    best_score = -1
    best_common_words = set()
    best_example = ""

    for intent in intents:
        score, common_words, example = score_intent(intent, user_sentence)

        if score > best_score:
            best_score = score
            best_intent = intent
            best_common_words = common_words
            best_example = example

    return best_intent, best_score, best_common_words, best_example


print("Meaning Chatbot started.")
print("Type quit to stop.")

while True:
    user_sentence = input("\nYou: ").strip()

    if user_sentence.lower() == "quit":
        print("Bot: Goodbye.")
        break

    intent, score, common_words, example = chatbot_reply(user_sentence)

    print("\nDetected intent:", intent["name"])
    print("Matched example:", example)
    print("Confidence score:", round(score, 3))
    print("Common meaning words:", common_words)

    if score < 0.05:
        print("Bot: I am not sure what you mean. Please say it differently.")
    else:
        print("Bot:", intent["reply"])

Student tasks

Assignments

Assignment A: Add music intent

  1. Add an intent named music.
  2. Add examples like I want songs, play music, I want to listen.
  3. Add a reply such as You may want to listen to music.

Assignment B: Make a learning chatbot

  1. Create intents for Python, AI, DSA, HTML, and Angular.
  2. Each intent should have at least 3 examples.
  3. Each reply should suggest a lesson.

Important limitations

This is not a full AI chatbot yet

What it can do

  • Compare user input with known intents.
  • Use WordNet synonym expansion.
  • Select the closest reply.
  • Show confidence score.

What it cannot do well

  • Understand deep context like a modern LLM.
  • Handle every real-world sentence perfectly.
  • Automatically create new answers.
  • Understand emotion deeply.
Next step after 70%: improve chatbot quality using better preprocessing, lemmatization, stop words, vectorization, and later embeddings.

Practice

Embedded Python Editor

Paste the final chatbot code into the editor. If the editor environment does not have NLTK installed, run it locally or in a Python notebook that allows package installation.

70% checkpoint

Revision Test

What is a chatbot?

A chatbot is a program that receives a user sentence and gives a useful reply.

What is an intent?

An intent is the purpose behind the user’s sentence.

Why does exact matching fail?

Because users may use different words to express the same meaning.

What does WordNet help us do?

It helps us find related words and expand sentence meaning using synonyms.

What does sentence_meaning_score() return?

It returns a score and the common meaning words between two sentences.

Why do we need many examples for one intent?

Because users may express the same intent in many different ways.

What is a confidence score?

It is a number showing how strongly the chatbot matched the user sentence with an intent.

What should the bot do when the score is very low?

It should say that it is not sure and ask the user to say it differently.

One-Line Summary

A meaning-based chatbot compares the user’s sentence with stored intents and chooses the reply whose meaning is closest.

Back to top