Natural Language Processing (NLP)
Objective
Set up a Python environment and learn to process text for chatbot projects. This chapter covers tokenization, lemmatization, part-of-speech tagging, named entity recognition, regular expressions, and ways to represent text numerically, including bag of words, TF-IDF, and embeddings.
3.1 Artificial Intelligence
Artificial intelligence (AI) is one of the most consequential technologies of the twenty-first century (Ribeiro 2025). The term covers a broad field, and its meaning depends on the task at hand. Popular culture offers familiar examples, from HAL 9000 in Stanley Kubrick’s 2001: A Space Odyssey to the operating system with whom a man falls in love in Her.
Intelligence takes many forms. Humans share some abilities with other animals, from responding to a hot surface to navigating an environment. Other abilities draw on specialized knowledge, such as answering an exam question about anatomy or drafting an appeal against an examination ruling. A program that performs a task associated with intelligent behavior can be studied as an AI system. The relevant question is what the system can do and under what conditions.
The everyday meaning of the words artificial and intelligence helps explain why people in many professions see the field as relevant. My dentist once asked how AI might affect dental procedures. The Fourier transform already has applications in many fields, but it had never prompted the same question (Wikipedia 2024). In computer science, Russell and Norvig describe AI as a field concerned with understanding intelligence and building intelligent entities (Russel and Norving 2013).
John McCarthy and his colleagues helped establish the term in computer science through the 1956 Dartmouth summer research project (blipblog 2024). Alan Turing had already raised the question of machine intelligence in his 1950 paper (Turing 1950). Imagined artificial beings are older still. Talos, the bronze guardian of Crete in Greek mythology, is one example (Pickover 2021).
In the 1970s, expert systems became one of the early practical approaches. Domain specialists helped turn knowledge drawn from experience into explicit rules. An inference engine applied those rules to the facts available to it. Eliciting and formalizing expert knowledge was labor-intensive, which made these systems difficult to build and maintain at scale. Figure 3.1 shows the interface of ExpertSinta, an expert-system tool.

Figure 3.1. The ExpertSinta expert-system interface.
Advances in computing power, storage, and the availability of data made other approaches more practical. One of the most important for language processing is machine learning.
3.2 Machine Learning
Machine learning is a branch of AI that uses data to build models. In an expert system, people must write down the knowledge the program will use. In machine learning, a training algorithm looks for patterns in examples and uses them to fit a model. The goal is for the model to work on examples it did not see during training.
Figure 3.2 illustrates four familiar applications: a voice assistant giving a weather update, a smart thermostat adapting to a person’s preferences, a self-driving car navigating a city street, and an online store recommending products based on past purchases. The illustration was generated with DALL-E 3.

Figure 3.2. Examples of machine learning in everyday applications.
Predictive tasks estimate a target for a new example. Classifying a message as a billing or shipping question is a classification task because the target is a category. Estimating the time remaining before delivery is a regression task because the target is a numerical quantity. Descriptive tasks look for structure in the data without a designated target. Clustering groups similar examples, association analysis finds patterns that occur together, and summarization produces a compact description of a data set.

Figure 3.3. Predictive and descriptive machine learning tasks.
These examples illustrate inductive learning, which draws general patterns from specific observations. The rest of this chapter focuses on the techniques most useful for working with chatbot text.
3.3 Natural Language Processing
Natural language processing (NLP) develops computational methods for analyzing, interpreting, and producing human language (Zhao et al. 2020). A system can work at several levels. It may analyze sounds, word forms, vocabulary, sentence structure, meaning, relationships across sentences, or what a speaker is trying to accomplish in a particular context.
Two longstanding approaches are symbolic and statistical NLP (Zhao et al. 2020). Symbolic systems apply explicit rules, grammars, or ontologies. A carefully written rule can handle a narrow task reliably, as ELIZA illustrates. It takes ongoing work to cover unfamiliar wording, ambiguity, and exceptions. Statistical methods learn patterns from collections of text called corpora. They helped advance spelling correction, machine translation, and voice assistants well before the emergence of ChatGPT (Celebrone 2025).
In a chatbot, NLP can help identify what the user wants. “Will it rain today?” and “What’s today’s weather forecast?” can both map to a weather intent. Embeddings capture similarities in wording and meaning, and a classifier trained on several ways to ask the same question can use those similarities to recognize the intent (Celebrone 2025).
The system may first clean and tokenize the incoming text. It can then extract details such as dates, names, and places. A weather request, for example, may contain both a location and a time. Those details help determine whether the system can answer immediately or should ask a follow-up question.
Earlier chatbots often selected canned replies. Modern generative chatbots can produce new responses and adjust their wording to the conversation. Chapter 4 explains how large language models do this. The sections below introduce the individual tools you can use to build and inspect a text-processing pipeline.
3.4 Setting Up Python
Use Python 3.12 for this chapter’s examples. The original edition primarily used Visual Studio Code, with some examples run in Google Colab. The packages, data files, and model versions used in each example can affect the output.
-
On Windows, get Python from https://www.python.org/ and follow the installer prompts.
-
On macOS, you can install Python through Homebrew with
brew install python. -
On Linux, use your distribution’s package manager and check the version with
python3 --version.
Use a virtual environment to keep the chapter’s packages separate from other projects. Run the following commands in order. On Windows, use PowerShell. On macOS or Linux, use the shell commands in the next listing.
py -3.12 -m venv .venv
.\.venv\Scripts\Activate.ps1
python3.12 -m venv .venv
source .venv/bin/activate
NumPy and pandas provide numerical and tabular data tools. Scikit-learn offers machine learning algorithms and vectorizers. NLTK provides language-processing tools and corpora often used in teaching and research. spaCy offers trained pipelines for tasks such as tokenization, part-of-speech tagging, lemmatization, named entity recognition, and dependency parsing. Gensim supports topic modeling, similarity analysis, and word vectors.
python -m pip install numpy pandas scikit-learn nltk spacy gensim
Run this script to confirm that the packages import and see which versions the environment is using.
import gensim
import nltk
import numpy
import pandas
import sklearn
import spacy
for package in (numpy, pandas, sklearn, nltk, spacy, gensim):
print(f"{package.__name__}: {package.__version__}")
JupyterLab lets you combine code, explanations, visualizations, and results in a notebook. Install and launch it from the same environment.
python -m pip install jupyterlab
jupyter lab
Create a Python notebook in the browser. Paste the following into a code cell and run it. The output appears beneath the cell.
a = 10
b = 20
print("The sum is:", a + b)
The sum is: 30
3.5 Core NLP Techniques
3.5.1 Tokenization
Tokenization splits text into units that a program can process (Jurafsky and Martin 2023). A word tokenizer may split “I am happy.” into four tokens, including the period. A sentence tokenizer instead marks where sentences begin and end. Tokenizers must decide how to handle punctuation, abbreviations, contractions, and compound words. The best choice depends on the language and the task. A system that identifies place names, for example, may tokenize “New York” as two words and then recognize the pair as one entity.
Some tokenizers use hand-written rules. Others learn a vocabulary or segmentation from data. Splitting on whitespace is a useful baseline for some languages, but it misses punctuation and does not address languages such as Chinese, where spaces do not generally mark word boundaries.
import nltk
from nltk.tokenize import sent_tokenize, word_tokenize
nltk.download("punkt_tab")
text = "Chatbots answer questions. They can also help with tasks."
print("Words:", word_tokenize(text))
print("Sentences:", sent_tokenize(text))
Words: ['Chatbots', 'answer', 'questions', '.', 'They', 'can',
'also', 'help', 'with', 'tasks', '.']
Sentences: ['Chatbots answer questions.',
'They can also help with tasks.']
spaCy can tokenize text without loading a trained model. An English pipeline with a trained model is useful when the next step requires part-of-speech tags, lemmas, or entities.
import spacy
nlp = spacy.blank("en")
doc = nlp("Chatbots answer questions.")
print([token.text for token in doc])
['Chatbots', 'answer', 'questions', '.']
3.5.2 Lemmatization
Lemmatization maps an inflected word to its dictionary form, or lemma (Singh et al. 2019). The verb “ran” has the lemma “run.” The noun “runners” has the lemma “runner.” A lemmatizer may need the part of speech to distinguish possible analyses.
import nltk
from nltk.stem import WordNetLemmatizer
nltk.download("wordnet")
lemmatizer = WordNetLemmatizer()
words = [("running", "v"), ("ran", "v"), ("runners", "n")]
print([lemmatizer.lemmatize(word, pos) for word, pos in words])
['run', 'run', 'runner']
To let spaCy infer grammatical categories from context, install an English pipeline with python -m spacy download en_core_web_sm in the same environment.
import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("The runners were training.")
for token in doc:
print(token.text, token.lemma_)
3.5.3 Stemming
A stemmer reduces related word forms using rules, often by stripping suffixes. A stem need not be a dictionary word. For example, the Porter stemmer maps “connection” and “connections” to “connect,” but it does not map the irregular verb “ran” to “run.”
from nltk.stem import PorterStemmer
stemmer = PorterStemmer()
words = ["running", "ran", "runners", "connection", "connections"]
print([stemmer.stem(word) for word in words])
['run', 'ran', 'runner', 'connect', 'connect']
3.5.4 Stop Words
Stop words are frequent words such as “the” and “and.” Filtering them can help a simple retrieval system focus on content words (Raj 2019). For tasks that depend on negation, a stop-word list can remove essential information. For example, “I want to cancel” and “I do not want to cancel” express different requests.
import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
nltk.download("punkt_tab")
nltk.download("stopwords")
stop_words = set(stopwords.words("english")) - {"no", "not", "nor"}
text = "The chatbot can answer the question."
content_words = [
token for token in word_tokenize(text)
if token.isalpha() and token.lower() not in stop_words
]
print(content_words)
['chatbot', 'answer', 'question']
import spacy
nlp = spacy.blank("en")
doc = nlp("The chatbot can answer the question.")
content_words = [
token.text for token in doc
if token.is_alpha and (not token.is_stop or token.lower_ in {"no", "not", "nor"})
]
print(content_words)
3.6 Other NLP Techniques
Part-of-speech tagging. A tagger assigns a grammatical category to each token. In “I am building chatbots,” it may label “I” as a pronoun, “am” as an auxiliary verb, “building” as a verb, and “chatbots” as a noun.
Named entity recognition. A recognizer identifies spans such as people, organizations, places, dates, and monetary amounts. In “Google is headquartered in Mountain View, California,” an English pipeline may identify Google as an organization and the two place names as geopolitical entities. Entity types and boundaries depend on the model.
Dependency parsing. A parser analyzes grammatical relationships between tokens. In “Book a flight from Corumbá to Maceió,” the verb “Book” anchors the request and the phrases headed by “from” and “to” signal the origin and destination. Those relationships can help a chatbot fill the right fields for a booking.
Text classification. A classifier assigns text to predefined categories. In an intent classifier, each category represents a kind of request, such as asking for a refund or tracking a shipment. Training typically requires examples labeled with the intended category. Naive Bayes is one possible baseline. It uses Bayes’ theorem with simplifying assumptions about the independence of features given the class.
3.7 Regular Expressions
A regular expression, or regex, describes a text pattern. Literal characters match themselves, and metacharacters describe alternatives, repetitions, or positions. In a chatbot, a regex can extract an order number, check the shape of a date, recognize a slash command, normalize whitespace, or provide a simple tokenizer. Some chatbot frameworks also use regex patterns as features for entity extraction.
Python’s re module offers several ways to apply a pattern:
-
re.matchchecks for a match at the beginning of the string. -
re.searchfinds the first match anywhere in the string. -
re.fullmatchrequires the entire string to match. -
re.findallreturns all non-overlapping matches. Capturing groups affect the form of the returned values. -
re.subreplaces matches and returns the resulting string.
Extracting Email Addresses
Use a pattern to find email-like strings in a message. This is a practical extractor for common addresses. A matching string can still refer to a mailbox that does not exist.
import re
text = "Contact sales@example.com or support@example.org."
email_pattern = r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b"
print(re.findall(email_pattern, text))
['sales@example.com', 'support@example.org']
Validating Dates
Use fullmatch to check the complete format, then parse the date to catch impossible calendar values. This example uses ISO-style year-month-day order.
import re
from datetime import date
def is_valid_date(value):
if not re.fullmatch(r"[0-9]{4}-[0-9]{2}-[0-9]{2}", value):
return False
try:
date.fromisoformat(value)
except ValueError:
return False
return True
for value in ("2025-06-25", "2025-02-29", "25/06/2025", "2025-06-25 10:00"):
print(value, is_valid_date(value))
2025-06-25 True
2025-02-29 False
25/06/2025 False
2025-06-25 10:00 False
Recognizing Commands
A messaging interface can use slash commands to route requests. The pattern below checks the shape of a command. A separate lookup can decide whether the command is supported.
import re
for value in ("/help", "/start", "help", "start/"):
print(value, bool(re.fullmatch(r"/[a-z][a-z0-9_]*", value)))
/help True
/start True
help False
start/ False
Simple Tokenization and Text Cleaning
\W+ matches runs of non-word characters. Splitting on it provides a quick baseline. Filtering out empty strings removes the empty token that a delimiter at the end can produce. This approach splits contractions and discards punctuation, so use it only when those details are irrelevant.
import re
text = "Hello, how are you?"
print([token for token in re.split(r"\W+", text) if token])
print(re.sub(r"\s+", " ", "Hello, how are you?\n").strip())
['Hello', 'how', 'are', 'you']
Hello, how are you?
For HTML documents, use a parser that knows how to handle nested markup, comments, and character references. The standard-library parser below collects the character data in a small, controlled fragment.
from html.parser import HTMLParser
class TextExtractor(HTMLParser):
def __init__(self):
super().__init__()
self.parts = []
def handle_data(self, data):
self.parts.append(data)
parser = TextExtractor()
parser.feed("<p>This paragraph contains <b>bold text</b>.</p>")
parser.close()
print("".join(parser.parts))
This paragraph contains bold text.
Lookaheads and lookbehinds check what follows or precedes a position without consuming that surrounding text. Quantifiers such as * and + are greedy by default. Adding ? makes them prefer a shorter match, subject to the rest of the pattern. Regex works well for predictable surface forms. Understanding that “Where is my package?” and “Has my order shipped?” are related requires information beyond those forms.
3.8 Natural Language Understanding
Natural language understanding (NLU) focuses on inferring meaning from language. Its applications include question answering, natural-language search, sentiment analysis, and extracting relationships between entities. In a task-oriented chatbot, an NLU component typically identifies an intent and extracts the details needed to act on it.
Consider the request “Book a flight from Corumbá to Maceió tomorrow.” The intent is to book a flight. The relevant details are the origin, destination, and date. A named entity recognizer can identify city names and date phrases. The application still has to assign each detail to the correct field and resolve “tomorrow” using the relevant date and time zone.
Users do not always follow expected wording. They make typos, use abbreviations, and refer to earlier turns. Normalization and lemmatization can help with some variation. Similarity search and trained classifiers can handle some paraphrases. Dialogue state supplies details left implicit in a follow-up such as “What about Friday?”
A typical pipeline converts the message into a structured representation for the dialogue or business logic. That logic can look up information, call an API, ask for a missing detail, or select a reply. Natural language generation (NLG) is the step that turns the result into a message the user can read.
3.8.1 Intents
An intent describes what the user wants to accomplish (Khan and Das 2018). A clothing store might distinguish product search from finding a store address. A food-ordering chatbot might distinguish checking prices from placing an order. An intent classifier learns to predict the label from messages annotated with the corresponding intent.
3.8.2 Utterances
An utterance is a message or conversational turn. “I’d like to order,” “Can I get some food?”, and “How do I place an order?” can all be examples of an order intent. Include a range of realistic phrasings for each intent and keep separate examples for evaluation. Near-duplicates split between training and evaluation can make the classifier look better than it performs on new messages.
3.8.3 Entities
Entities are spans of text that carry details relevant to an intent. In “I’d like a pepperoni pizza with a stuffed crust,” the order intent is accompanied by a product, a topping, and a crust preference. Those values can populate fields in the order. Their types and allowed values depend on the application.
3.8.4 Practical Challenges
A trained system must predict intents and extract entities for utterances it has never seen. Many classifiers return a score along with their prediction. Use examples held out from training to choose a threshold for asking a follow-up question or offering a fallback. Treat the score as a model output whose reliability must be checked against data. It may not be a calibrated probability.
Once the chatbot has enough information, it can route the request to the appropriate action. Aggregated intent counts can reveal what users ask for most often. Review ambiguous and unrecognized requests as well, since the most frequent predicted labels may hide systematic classification errors.
Language remains ambiguous even when every word is recognized. A coherent response needs grammatical structure, the intended meaning, and enough context to interpret references to earlier turns. When several interpretations are plausible and the stakes of a wrong choice are meaningful, the chatbot can ask a focused question before proceeding.
3.9 Text Vectorization and Representation
A text representation maps words, messages, or documents to numbers that an algorithm can compare and process. The choice determines which properties survive the conversion. A word-count vector can show whether “refund” appears in a message. A dense embedding can help match related expressions such as “refund” and “get my money back.”
3.9.1 One-Hot Encoding
A one-hot vector represents a categorical value using a single 1 and zeros elsewhere. Each position belongs to one item in a fixed vocabulary. The vectors keep categories distinct, while the distance between two different vectors tells us nothing about how closely the words are related.
from sklearn.preprocessing import OneHotEncoder
encoder = OneHotEncoder(sparse_output=False, handle_unknown="ignore")
vectors = encoder.fit_transform([["book"], ["cancel"], ["track"]])
print(encoder.categories_[0].tolist())
print(vectors.astype(int))
['book', 'cancel', 'track']
[[1 0 0]
[0 1 0]
[0 0 1]]
3.9.2 Bag of Words (BoW)
Bag of words represents a document by the counts of its vocabulary terms. Each row is a document and each column is a word. The representation discards word order. For example, “dog bites man” and “man bites dog” have the same word counts.
from sklearn.feature_extraction.text import CountVectorizer
documents = ["book a flight", "cancel a flight", "track a flight"]
vectorizer = CountVectorizer()
counts = vectorizer.fit_transform(documents)
print(vectorizer.get_feature_names_out().tolist())
print(counts.toarray())
['book', 'cancel', 'flight', 'track']
[[1 0 1 0]
[0 1 1 0]
[0 0 1 1]]
The default tokenizer skips single-character words such as “a.” The returned matrix is sparse. It stores the nonzero entries efficiently, which matters when the vocabulary has thousands of columns. Here toarray() makes the small example easier to read. Use ngram_range=(1, 2) to include adjacent word pairs when phrases such as “credit card” matter.
3.9.3 TF-IDF
Term frequency–inverse document frequency (TF-IDF) gives more weight to words that occur in a document but are less common across the collection. The inverse document frequency depends on how many documents contain the term. In the previous example, “flight” occurs in every message, so it contributes less to distinguishing them than “book,” “cancel,” or “track.”
from sklearn.feature_extraction.text import TfidfVectorizer
documents = ["book a flight", "cancel a flight", "track a flight"]
vectorizer = TfidfVectorizer()
weights = vectorizer.fit_transform(documents)
print(vectorizer.get_feature_names_out().tolist())
print(weights.toarray().round(3))
['book', 'cancel', 'flight', 'track']
[[0.861 0. 0.509 0. ]
[0. 0.861 0.509 0. ]
[0. 0. 0.509 0.861]]
Scikit-learn smooths the inverse document frequency and normalizes each row by default. Other tools may use a different formula or normalization. Like basic bag of words, TF-IDF depends on matching vocabulary terms and does not preserve their order.
3.9.4 Choosing and Applying a Representation
One-hot encoding works for individual categories. Bag of words is a useful baseline when repeated terms carry information. TF-IDF is useful for text search and classifiers that benefit from emphasizing distinctive terms. Embeddings are useful when messages may express related ideas with different words. Choose a representation by measuring how well it serves the task on examples held out for evaluation.
The following toy classifier combines TF-IDF with multinomial naive Bayes. The pipeline learns the vocabulary and weights from the training examples. When it predicts on the new messages, it applies that same transformation. In a real evaluation, keep the test examples separate before fitting any preprocessing step.
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import make_pipeline
messages = [
"excellent service and fast delivery",
"excellent product and friendly support",
"fast service and a great experience",
"terrible service and slow delivery",
"terrible product and poor support",
"slow service and a disappointing experience",
]
labels = ["positive"] * 3 + ["negative"] * 3
model = make_pipeline(TfidfVectorizer(), MultinomialNB())
model.fit(messages, labels)
print(model.predict(["excellent and fast", "terrible and slow"]).tolist())
['positive', 'negative']
These two predictions illustrate the pipeline. To evaluate a useful classifier, collect enough labeled examples to cover realistic phrasing, including mixed sentiments and negation. Report results on a separate test set and inspect the kinds of messages the classifier gets wrong.
3.9.5 Word Embeddings
A word embedding represents a word as a dense vector. Training brings together words that appear in related contexts. Cosine similarity measures how closely two vectors point in the same direction. It can find related words, but the relationship may reflect topic, syntax, or training-data biases. Static embeddings assign one vector to a word even when the word has several meanings. Contextual models can produce different representations for a token in different sentences.
3.9.6 Word2Vec
Word2Vec learns embeddings from nearby words. Continuous bag of words (CBOW) predicts a target word from its neighbors. Skip-gram uses a target word to predict nearby words. Gensim selects CBOW with sg=0 and skip-gram with sg=1.
import nltk
from gensim.models import Word2Vec
from nltk.corpus import brown
nltk.download("brown")
sentences = [
[word.lower() for word in sentence if word.isalpha()]
for sentence in brown.sents(categories="news")
]
model = Word2Vec(
sentences, vector_size=100, window=5, min_count=5, sg=0, workers=1
)
print(model.wv["government"].shape)
print(model.wv.most_similar("government", topn=3))
The first line should show a vector of length 100. The neighbors depend on the training data and settings. Vector arithmetic can also be explored with most_similar(positive=["king", "woman"], negative=["man"]) when all three terms are in the vocabulary. A small corpus may miss one of those words or return unexpected neighbors. Treat analogies as a diagnostic, not as a guarantee of understanding.
3.9.7 GloVe
GloVe learns vectors from global word co-occurrence counts. You can load pretrained vectors to experiment without training a model. The following example uses an English model available through the Gensim downloader. The first run downloads the data into the local cache.
import gensim.downloader as api
vectors = api.load("glove-wiki-gigaword-50")
print(vectors["economy"].shape)
print(vectors.most_similar("economy", topn=3))
3.9.8 FastText
FastText represents a word using character sequences as well as information about the word itself. This helps relate words with common prefixes or suffixes and lets the model construct a vector for some words it did not encounter during training.
import nltk
from gensim.models import FastText
from nltk.corpus import brown
nltk.download("brown")
sentences = [
[word.lower() for word in sentence if word.isalpha()]
for sentence in brown.sents(categories="news")
]
model = FastText(sentences, vector_size=100, window=5, min_count=5, workers=1)
word = "hyperlocalization"
print(word in model.wv.key_to_index)
print(model.wv[word].shape)
The first line checks whether the word appears in the stored vocabulary. Even when it prints False, the model can construct a 100-dimensional vector from the word’s character sequences. That vector can be useful for spelling variants or rare words. Its quality depends on what the model learned about those sequences.
3.10 Summary
Tokenization splits text into units. Lemmatization and stemming reduce different word forms, and stop-word filtering removes selected frequent terms. Regular expressions extract or validate predictable patterns. In a chatbot, natural language understanding can identify the intent behind an utterance and extract the entities that a downstream action needs.
One-hot vectors identify categories. Bag-of-words and TF-IDF vectors represent documents using vocabulary terms, with TF-IDF placing more weight on terms that are distinctive across the collection. Word2Vec, GloVe, and FastText learn dense word vectors from text. The usefulness of any representation depends on the task and how it performs on new examples.