Streamlining Text Preprocessing Techniques for NLP
local graph
Chapter 4 — Streamlining Text Preprocessing Techniques for NLP
Section titled “Chapter 4 — Streamlining Text Preprocessing Techniques for NLP”Text preprocessing stands as a vital initial step in the realm of natural language processing (NLP). It encompasses converting raw, unrefined text data into a format that machine learning algorithms can readily comprehend. To extract meaningful insights from textual data, it is essential to clean, normalize, and transform the data into a more structured form. This chapter provides an overview of the most commonly used text preprocessing techniques, including tokenization, stemming, lemmatization, stop word removal, and part-of-speech (POS) tagging, along with their advantages and limitations.
Effective text preprocessing is essential for various NLP tasks, including sentiment analysis, language translation, and information retrieval. By applying these techniques, raw text data can be transformed into a structured and normalized format that can be easily analyzed using statistical and machine learning methods. However, selecting the appropriate preprocessing techniques can be challenging since the optimal methods depend on the specific task and dataset at hand. Therefore, it is important to carefully evaluate and compare different text preprocessing techniques to determine the most effective approach for a given application.
This chapter covers the following topics:
- Remove and decode encoding artifacts
- Lowercasing in NLP
- Converting digits to words
- Spelling correction
- Removing special characters and punctuations
- Removing stop words
- Named entity recognition (NER)
- POS tagging
- Explaining the preprocessing pipeline
Technical requirements
Section titled “Technical requirements”To follow along with the examples and exercises in this chapter on text preprocessing, you will need a working knowledge of a programming language such as Python, as well as some familiarity with NLP concepts. You will also need to have certain libraries installed, such as Natural Language Toolkit (NLTK), spaCy, and Scikit-Learn. These libraries provide powerful tools for text preprocessing and feature extraction. It is recommended that you have access to a Jupyter Notebook environment or another interactive coding environment to facilitate experimentation and exploration. Additionally, having a sample dataset to work with can help you understand the various techniques and their effects on text data.
Text normalization is the process of transforming text into a standard form to ensure consistency and reduce variations. Different techniques are used for normalizing text, including lowercasing, removing special characters, spell checking, and stemming or lemmatization. We will explain these steps in detail and show how to use them with code examples.
Remove and decode encoding artifacts
Section titled “Remove and decode encoding artifacts”In many real-world NLP settings, the input text is not a clean sentence but a serialized payload extracted from web pages, emails, logs, or enterprise systems. Such data often contains markup-like wrappers (for example, HTML tags, XML fields, or application-specific delimiters) that were useful for transport or display but are irrelevant—or even harmful—for downstream modeling. A typical example is an email body embedded inside structural tokens (e.g., <SUBJECT LINE> … <END> <BODY TEXT> … <END>), or text scraped from HTML that includes tags, attributes, and escaped characters. The goal of decoding and removing these encoding artifacts is to recover the intended human-readable content while discarding the scaffolding that only reflects formatting and metadata.
This step usually combines two operations. First, decoding reverses transport transformations such as HTML entities (e.g., converting & back to &) and escaped sequences (e.g., converting \n into a newline). Second, tag removal strips markup tokens while preserving the underlying textual content. In practice, the implementation must be careful not to accidentally delete meaningful text (for example, URLs, email addresses, or domain-specific markers). When performed correctly, decoding and tag removal reduce noise, stabilize tokenization, and prevent spurious vocabulary growth caused by bracketed strings, tag names, and formatting fragments that carry no linguistic meaning.
Lowercasing in NLP
Section titled “Lowercasing in NLP”Lowercasing is a common text preprocessing technique that’s used in NLP to standardize text and reduce the complexity of vocabulary. In this technique, all the text is converted into lowercase characters.
The main purpose of lowercasing is to make the text uniform and avoid any discrepancies that may arise from capitalization. By converting all the text into lowercase, machine learning algorithms can treat the same words that are capitalized and non-capitalized as the same, reducing the overall vocabulary size and making the text easier to process.
Lowercasing is particularly useful for tasks such as text classification, sentiment analysis, and language modeling, where the meaning of the text is not affected by the capitalization of the words. However, it may not be suitable for certain tasks, such as NER, where capitalization can be an important feature.
Converting digits to words
Section titled “Converting digits to words”Text often contains numerical expressions—counts, dates, times, dosages, monetary values, identifiers, and ordinal forms such as “1st” or “2nd.” Whether these numbers should remain numeric or be converted into words depends on the task and the expected modeling approach. Many classical natural language processing pipelines (and even some modern models used in constrained settings) benefit from mapping digits to their written form because it reduces superficial variation and improves consistency.
For example, “2 files” and “two files” convey the same meaning, but treating them as separate surface forms can inflate the vocabulary and fragment statistics in bag-of-words or TF–IDF representations. Converting digits to words is therefore a normalization step that aims to unify semantically equivalent expressions and increase model robustness.
A well-designed conversion procedure should handle cardinal numbers (“2” → “two”), ordinals (“1st” → “first”), and common numeric patterns such as times (“4pm” → “four pm” or “4 pm,” depending on the normalization policy). This is not merely cosmetic: numerical normalization influences tokenization boundaries, affects downstream lemmatization or stemming, and can simplify the feature space used by traditional machine learning models. At the same time, some tasks—such as financial prediction, medical dosage extraction, or ID matching—require preserving the exact numeric value. For that reason, digit-to-word conversion is best treated as a configurable step, applied when linguistic consistency is more important than numerical precision.
Spelling correction
Section titled “Spelling correction”Spelling errors are pervasive in user-generated text and operational datasets, arising from typos, OCR artifacts, phonetic spellings, and domain-specific shorthand. These errors introduce sparsity into the vocabulary: a misspelled word becomes a separate token that may occur rarely, weakening statistical signals and confusing downstream models. For instance, “healthcare” and “healtcare” refer to the same concept, but they appear as distinct surface forms unless the pipeline corrects them. Spelling correction mitigates this problem by mapping nonstandard variants to a canonical form, thereby improving vocabulary consistency and increasing the effective frequency of meaningful tokens.
Spelling correction is typically applied after basic cleaning steps (such as lowercasing and punctuation handling) so the correction model sees a more standardized input. Methods range from dictionary-based approaches and edit-distance heuristics to context-aware models that use surrounding words to infer the most plausible correction. Regardless of the method, a practical implementation must balance correction coverage with the risk of “overcorrection,” where valid domain terms, names, or abbreviations are incorrectly rewritten. In technical corpora, such as medical notes, legal documents, or internal enterprise text, this risk is especially pronounced. For this reason, spelling correction is often augmented with custom vocabularies, whitelists, or domain-specific lexicons, ensuring that specialized terminology is preserved while genuine errors are normalized.
Removing special characters and punctuation
Section titled “Removing special characters and punctuation”Removing special characters and punctuation is an important step in text preprocessing. Special characters and punctuation marks do not add much meaning to the text and can cause issues for machine learning models if they are not removed. One way to perform this task is by using regular expressions, such as the following:
re.sub(r”[^a-zA-Z0-9]+”, “”, string)This will remove non alphanumeric characters from our input string. Sometimes, there may be special characters that we want to replace with a whitespace. Take a look at the following examples:
- president-elect
- body-type
In these two examples, we would want to replace the “-” with whitespace, as follows:
- President elect
- Body type
Once we are done with lowercasing and removing special characters, we’ll cover stop word removal.
Stop word removal
Section titled “Stop word removal”Stop words are words that do not contribute much to the meaning of a sentence or piece of text, and therefore can be safely removed without our losing much information. Examples of stop words include “a,” “an,” “the,” “and,” “in,” “at,” “on,” “to,” “for,” “is,” “are,” and so on.
Stop word removal is a common text preprocessing step that is performed before any text analysis tasks, such as sentiment analysis, topic modeling, or information retrieval. The goal is to reduce the size of the vocabulary and the dimensionality of the feature space, which can improve the efficiency and effectiveness of subsequent analysis steps.
The process of stop word removal involves identifying a list of stop words (usually predefined or learned from a corpus), tokenizing the input text into words or tokens, and then removing any words that match the stop word list. The resulting text consists of only the important words that carry the meaning of the text.
Stop word removal can be performed using various programming languages, tools, and libraries. For example, NLTK, which is a popular Python library for natural language processing, provides a list of stop words for various languages, as well as a method for removing stop words from text.
Here’s an example of stop word removal:
This is a sample sentence demonstrating stop word filtration.After performing stop word removal, we get the following output:
Sample sentence demonstrating stop word filtrationThis chapter contains Python code examples for each of the preprocessing steps described. You can refer to it for each of the actions that are described in this chapter.
As we can see, the stop words “This,” “is,” “a,” and “the” have been removed from the original sentence, leaving only the important words. Once we normalize and clean the text, we can apply spelling correction and then remove stop words. This will ensure that the stop words are properly identified and removed.
Spell checking and correction
Section titled “Spell checking and correction”Spell checking and correction involves correcting misspelled words in the text. This is important because misspelled words can cause inconsistencies in the data and affect the accuracy of algorithms. For example, take a look at the following sentence:
I am going to the bakkery.This would be transformed into the following:
I am going to the bakeryLemmatization
Section titled “Lemmatization”Lemmatization is a text normalization approach that aims to simplify a word to its base or dictionary form, referred to as a lemma. The primary objective of lemmatization is to aggregate various forms of the same word, facilitating their analysis as a unified term.
For example, consider the following sentence:
Three cats were chasing the mice in the fields, while one cat watched one mouse.In the context of this sentence, “cat” and “cats” are two different forms of the same word, and “mouse” and “mice” are also two different forms of the same word. Lemmatization would reduce these words to their base forms:
the cat be chasing the mouse in the field, while one cat watched one mouse.In this case, “cat” and “cats” have both been reduced to their base form of “cat,” and “mouse” and “mice” have both been reduced to their base form of “mouse.” This allows for better analysis of the text, since the occurrences of “cat” and “mouse” are now treated as the same term, regardless of their inflectional variations.
Another way to preprocess the words in the text is by stemming.
Stemming
Section titled “Stemming”Stemming involves reducing words to their fundamental or root form, referred to as the “stem.” This process is commonly used in NLP to prepare text for analysis, retrieval, or storage. Stemming algorithms work by cutting off the ends or suffixes of words, leaving only the stem.
The goal of stemming is to convert all inflected or derived forms of a word into a common base form. For example, the stem of the word “running” is “run,” and the stem of the word “runs” is also “run.”
One commonly used stemming algorithm is the Porter stemming algorithm. This algorithm is based on a series of rules that identify suffixes and remove them from words to obtain the stem. For example, the Porter algorithm would convert the word “leaping” into “leap” by removing the “ing” suffix.
Let’s look at an example sentence to see stemming in action:
They are running and leaping across the walls.Here’s the stemmed text (using the Porter algorithm):
They are run and leap across the wall.As you can see, the words “running” and “leaping” have been converted into their base forms of “run” and “leap,” respectively, and the suffix “s” has been removed from “walls.”
Stemming can be useful for text analysis tasks such as information retrieval or sentiment analysis, as it reduces the number of unique words in a document or corpus and can help to group similar words. However, stemming can also introduce errors, as it can sometimes produce stems that are not actual words or produce stems that are not the intended base form of the word.
Lemmatization is different from stemming, which involves reducing a word to a common stem that may not necessarily be a word in its own right. For example: “ The children were running faster and ate better foods.”
With stemming, words are reduced mechanically, so running becomes run, but ate, better, and children remain unchanged.
With lemmatization, linguistic meaning is considered, so ate becomes eat, better becomes good, and children becomes child. Lemmatization can be performed using various NLP libraries and tools such as NLTK, spaCy, and Stanford CoreNLP.
Once the preprocessing of the text is complete, we can perform different tasks on the text, such as Named Entity Recognition.
Named Entity Recognition (NER) is an NLP technique that’s designed to detect and categorize named entities within text, including person’s names, organization’s names, locations, and more. NER’s primary objective is to autonomously identify and extract information about these named entities from unstructured text data.
NER typically involves using machine learning models, such as conditional random fields (CRFs) or recurrent neural networks (RNNs), to tag words in a given sentence with their corresponding entity types. The models are trained on large annotated datasets that contain text with labeled entities. These models then use context-based rules to identify named entities in new text.
There are several categories of named entities that can be identified by NER, including the following:
- Person: A named individual, such as “Barack Obama”
- Organization: A named company, institution, or organization, such as “Google”
- Location: A named place, such as “New York City”
- Date: A named date or time, such as “January 1, 2023”
- Product: A named product or brand, such as “iPhone”
Here’s an example of how NER works. Take a look at the following sentence:
Apple Inc. is a technology company headquartered in Cupertino, California.Here NER would identify “Apple Inc.” as an organization and “Cupertino, California” as a location. The output of an NER system could be a structured representation of the sentence, as shown here:
{“organization”: “Apple Inc.”,“location”: “Cupertino, California”}NER has many applications in various fields, including information retrieval, question answering, sentiment analysis, and more. It can be used to automatically extract structured information from unstructured text data, which can be further analyzed or used for downstream tasks.
There are different approaches and tools to perform NER, but the general steps when performing NER are as follows:
- Data collection: The first step is to collect the data that will be used for NER. This data can be in the form of unstructured text, such as articles, social media posts, or web pages.
- Preprocessing: The next step is to preprocess the data, which involves various steps, such as tokenization, stop word removal, stemming or lemmatization, and normalization.
- Labeling: After preprocessing, the next step is to label the data with named entity tags. There are different tagging schemes, but one of the most commonly used is the Inside-Outside-Beginning (IOB) tagging scheme. In this scheme, each word in the text is labeled as either B (beginning of a named entity), I (inside a named entity), or O (outside a named entity).
- Training: Once the data has been labeled, the next step is to train a machine learning model to recognize named entities in new, unseen text. Different types of models can be used for NER, such as rule-based systems, statistical models, and deep learning models.
- Evaluation: After training the model, it is important to evaluate its performance on a test dataset. This can help identify any issues with the model, such as overfitting, underfitting, or bias.
- Deployment: Finally, the trained model can be deployed to perform NER on new, unseen text. This can be done in real time or in batch mode, depending on the application’s requirements.
Here’s an example of how NER can be performed:
Original text:
Apple is negotiating to buy a Chinese startup this year.Preprocessed text:
apple negotiating buy Chinese startup yearTagged text:
B-ORG O O B-LOC O OIn this example, the named entities “Apple” and “Chinese” are identified as an organization (B-ORG) and a location (B-LOC), respectively. “this year” is not recognized as a named entity in this example, but it would be if a more complex tagging scheme were used or if the model were trained on data that would promote that.
Several libraries can be used for NER, depending on the programming language and specific needs of the project. Let’s take a look at some commonly used libraries:
- spaCy: spaCy is a widely used open source library designed for various NLP tasks, including NER. Offering pre-trained models across multiple languages, the library additionally empowers users to undertake model training for distinct domains tailored to their specific needs.
- NLTK: Natural Language Toolkit (NLTK) is another widely used library for NLP tasks, including NER. It provides several pre-trained models and also allows users to train their models.
- Stanford NER: This is a Java-based NER tool that provides pre-trained models for several languages, including English, German, and Chinese.
- AllenNLP: AllenNLP is a popular open source library for building and evaluating NLP models, including NER. It provides pre-trained models for several tasks, including NER, and also allows users to train their own models.
- Flair: Flair is a Python library for state-of-the-art NLP, including NER. It provides pre-trained models for several languages and also allows users to train their own models.
- General Architecture for Text Engineering (GATE): This is a suite of tools for NLP, including NER. It provides a graphical interface for creating and evaluating NLP models and also allows users to develop custom plugins for specific tasks.
There are many other libraries available for NER, and the choice of library will depend on factors such as the programming language, available models, and specific requirements of the project. In the next section, we will explain POS tagging and different methods to perform this task.
POS tagging
Section titled “POS tagging”Part of speech (POS) tagging is the practice of attributing grammatical labels, such as nouns, verbs, adjectives, and others, to individual words within a sentence. This tagging process holds significance as a foundational step in various NLP tasks, including text classification, sentiment analysis, and machine translation.
POS tagging can be performed using different approaches, such as rule-based methods, statistical methods, and deep learning-based methods. In this section, we’ll provide a brief overview of each approach.
Rule-based methods
Section titled “Rule-based methods”Rule-based methods for POS tagging involve defining a set of rules or patterns that can be used to automatically tag words in a text with their corresponding parts of speech, such as nouns, verbs, adjectives, and so on.
The process involves defining a set of rules or patterns for identifying the different parts of speech in a sentence. For example, a rule may state that any word ending in “-ing” is a gerund (a verb acting as a noun), while another rule may state that any word preceded by an article such as “a” or “an” is likely a noun.
These rules are typically based on linguistic knowledge, such as knowledge of grammar and syntax, and are often specific to a particular language. They can also be supplemented with lexicons or dictionaries that provide additional information about the meanings and usage of words.
The process of rule-based tagging involves applying these rules to a given text and identifying the parts of speech for each word. This can be done manually, but is typically automated using software tools and programming languages that support regular expressions and pattern matching.
One advantage of rule-based methods is that they can be highly accurate when the rules are well-designed and cover a wide range of linguistic phenomena. They can also be customized to specific domains or genres of text, such as scientific literature or legal documents.
However, one limitation of rule-based methods is that they may not be able to capture the full complexity and variability of natural language, and may require significant effort to develop and maintain the rules as language evolves and changes over time. They may also struggle with ambiguity, such as in cases where a word can have multiple possible parts of speech depending on the context.
Despite these limitations, rule-based methods for POS tagging remain an important approach in NLP, especially for applications that require high accuracy and precision.
Statistical methods
Section titled “Statistical methods”Statistical methods for POS tagging are based on using probabilistic models to automatically assign the most likely POS tag to each word in a sentence. These methods rely on a training corpus of tagged text, where the POS tags have already been assigned to the words, to learn the probabilities of a particular word being associated with each tag.
Two main types of statistical methods are used for POS tagging: Hidden Markov Models (HMMs) and CRFs.
HMMs serve as a category of probabilistic models that are extensively applied in handling sequential data, including text. In the context of POS tagging, HMMs represent the probability distribution of a sequence of POS tags concerning a sequence of words. HMMs assume that the likelihood of a POS tag at a specific position within a sentence is contingent solely upon the preceding tag in the sequence. Furthermore, they presume that the likelihood of a particular word, given its tag, remains independent of other words within the sentence. To identify the most probable sequence of POS tags for a given sentence, HMMs employ the Viterbi algorithm.
CRFs are another type of probabilistic model that is commonly used for sequence labeling tasks, including POS tagging. CRFs differ from HMMs in that they model the conditional probability of the output sequence (that is, the POS tags) given the input sequence (that is, the words), rather than the joint probability of the output and input sequences. This allows CRFs to capture more complex dependencies between the input and output sequences than HMMs. CRFs use an iterative algorithm, such as gradient descent or L-BFGS, to learn the optimal set of weights for the model.
Let’s look at the advantages of statistical methods:
- Statistical methods can capture the context of a word and the relationships between words in a sentence, leading to more accurate tagging results
- These methods can handle unseen words and sentences that are not present in the training data
- Statistical methods can be trained on large datasets, allowing them to capture more variations and patterns in the language
Now, let’s look at the disadvantages:
- These methods require a large amount of annotated data for training, which can be time-consuming and expensive to create
- Statistical methods can be sensitive to the quality of the training data and may perform poorly if the data is noisy or biased
- Statistical models are typically black boxes, making it difficult to interpret the decisions made by the model
Another way to perform POS tagging is by using deep learning methods.
Deep learning-based methods
Section titled “Deep learning-based methods”Deep learning-based methods for POS tagging involve training a neural network model to predict the POS tags for each word in a given sentence. These methods can learn complex patterns and relationships in the text data to accurately tag words with their appropriate parts of speech.
One of the most popular deep learning-based methods for POS tagging is using a Recurrent Neural Network (RNN) with Long Short -Term Memory (LSTM) cells. LSTM-based models can process sequences of words and capture dependencies between them. The input to the model is a sequence of word embeddings, which are vector representations of words in a high-dimensional space. These embeddings are learned during the training process.
The LSTM-based model is composed of three main layers: an input layer, an LSTM layer, and an output layer. The structure involves taking word embeddings as input into the input layer. Subsequently, the LSTM layer processes the sequence of these embeddings, aiming to grasp the interdependencies inherent within them. Ultimately, the output layer is responsible for predicting the POS tag for each word within the input sequence. Another popular deep learning-based method for POS tagging is using a transformer-based model, such as Bidirectional Encoder Representations from Transformers (BERT). BERT is a language model that comes pre-trained and employs a transformer-based architecture to acquire a profound understanding of contextual relationships among words within a sentence. It undergoes training with vast quantities of text data and can be fine-tuned to excel in diverse NLP tasks, one of which is POS tagging.
To use BERT for POS tagging, the input sentence must be tokenized, and each token must be assigned an initial POS tag. The token embeddings are then fed into the pre-trained BERT model, which outputs contextualized embeddings for each token. These embeddings are passed through a feedforward neural network to predict the final POS tag for each token.
Deep learning approaches for POS tagging have demonstrated leading-edge performance across numerous benchmark datasets. Nonetheless, their effectiveness demands substantial training data and computational resources, and the training process can be time-consuming. Moreover, they may suffer from a lack of interpretability, which makes it difficult to understand how the model is making its predictions.
Several libraries are available for performing POS tagging in various programming languages, including Python, Java, and C++. Some popular NLP libraries that provide POS tagging functionality include NLTK, spaCy, Stanford CoreNLP, and Apache OpenNLP.
Here is an example of POS tagging using the NLTK library in Python:
import nltkinput_sentence = “The young white cat jumps over the lazy dog”processed_tokens = nltk.word_tokenize(input_sentence)tags = nltk.pos_tag(processed_tokens)print(tags)The output is as follows:
[(‘The’, ‘DT’), (‘young’, ‘JJ’), (‘white’, ‘JJ’), (‘cat’, ‘NN’), (‘jumps’, ‘VBZ’), (‘over’, ‘IN’), (‘the’, ‘DT’), (‘lazy’, ‘JJ’), (‘dog’, ‘NN’)]In this example, the nltk.pos_tag() function is used to tag the words in the sentence. The function returns a list of tuples, where each tuple contains a word and its POS tag. The POS tags used here are based on the Penn Treebank tagset.
Regular expression
Section titled “Regular expression”A regular expression is a type of text pattern that has various applications in modern programming languages and software. It is useful for validating whether an input conforms to a particular text pattern, locating text within a larger text body that matches the pattern, replacing text that matches the pattern with alternative text or rearranging parts of the matched text, dividing a block of text into a list of subtexts, and even causing unintended consequences if used incorrectly.
In computer science and mathematics, the term “ regular expression ” is derived from the concept of regularity in mathematical expressions.
A regular expression, often referred to as regex or regexp, is a series of characters that constitutes a search pattern. Regular expressions are used to match and manipulate text, typically in the context of text processing, search algorithms, and NLP.
A regular expression comprises a mix of characters and metacharacters, which collectively establish a pattern to search for within a text string. The simplest form of a regular expression is a mere sequence of characters that must be matched precisely. For example, the regular expression “hello” would match any string that contains the characters “hello” in sequence.
Metacharacters are unique characters within regular expressions that possess predefined meanings. For instance, the “.” (dot) metacharacter is employed to match any individual character, whereas the “*” (asterisk) metacharacter is used to match zero or more instances of the preceding character or group. Regular expressions can be used for a wide range of text-processing tasks. Let’s take a closer look.
Validating input
Section titled “Validating input”Regular expressions can be used to validate input by matching it against a pattern. For example, you can use a regular expression to validate an email address or a phone number.
Text manipulation
Section titled “Text manipulation”Text manipulation using regular expressions involves using pattern-matching techniques to find and manipulate text strings in a document or dataset. Regular expressions are powerful tools for working with text data, allowing for complex search and replace operations, text extraction, and formatting.
Some common text manipulation tasks that can be accomplished with regular expressions are as follows:
- Search and replace: Using regular expressions to search for specific patterns or character sequences in a document and replace them with other text or formatting
- Data extraction: Regular expressions can be used for data extraction from text by defining patterns that match specific data formats
Here are the general steps for using regular expressions for data extraction:
- Define a regular expression pattern: The first step is to define a regular expression pattern that matches the data you want to extract. For example, if you want to extract all phone numbers from a text document, you can define a pattern that matches the format of a phone number.
- Compile the regular expression pattern: After establishing the regular expression pattern, the next step is to compile it into a regular expression object, which can then be used for matching purposes.
- Search for the pattern in the text: Once you have compiled the regular expression object, you can use it to search for the pattern in the text. You can search for the pattern in a single string or a larger block of text.
- Extract the matched data: After you have searched for the pattern in the text, you can extract the data that matches that pattern. You can extract all occurrences of the matched data, or only the first occurrence.
Here’s an example of how to extract all email addresses from a string using regular expressions in Python:
import retext = “John’s email is [email protected] and Jane’s email is [email protected]”# Pattern for email addresses:pattern = r”\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b”regex = re.compile(pattern)# Search for all occurrences of the pattern in the text:matches = regex.findall(text)print(matches)Here’s the output:
Next, we’ll cover text cleaning.
Text cleaning
Section titled “Text cleaning”Text cleaning means using regular expressions to clean and standardize text data, thereby removing unwanted characters, whitespace, or other formatting.
Here are some common text-cleaning techniques that use regular expressions:
- Removing special characters: Regular expressions can be used to match and remove specific characters such as punctuation marks, brackets, and other special symbols. For example, the
[^a-zA-Z0-9]regular expression will match any non-alphanumeric character. - Removing stop words: Stop words are common words such as “the,” “and,” and “but” that are often removed from text to focus on the most meaningful words. Regular expressions can be used to match and remove these words from text.
- Removing HTML tags: If you’re working with text that has been scraped from a website, you may need to remove HTML tags before analyzing the text. Regular expressions can be used to match and remove HTML tags.
- Converting text into lowercase: Regular expressions can be used to convert all text into lowercase or uppercase, which can make it easier to compare and analyze.
- Normalizing text: Normalization involves transforming text into a standard format. Regular expressions can be used to perform tasks such as stemming and lemmatization, which involves reducing words to their root form.
By using regular expressions for text cleaning, you can remove noise and irrelevant information from text, making it easier to analyze and extract meaningful insights.
After text cleaning standardizes and removes noise from raw text, parsing can be applied to analyze the cleaned text’s grammatical structure in a more reliable and consistent manner.
Parsing
Section titled “Parsing”Parsing involves analyzing a text string to discern its grammatical structure according to a specified grammar. Regular expressions serve as potent instruments for text parsing, especially when dealing with uncomplicated and regular grammatical patterns.
To parse text using regular expressions, you need to define a grammar for the language you want to parse. The grammar should specify the possible components of a sentence, such as nouns, verbs, adjectives, and so on, as well as the rules that dictate how these components can be combined to form valid sentences.
Once you have defined the grammar, you can use regular expressions to identify the individual components of a sentence and the relationships between them. For example, you can use regular expressions to match all the nouns in a sentence, or to identify the subject and object of a verb.
One common approach to parsing with regular expressions is to define a set of patterns that correspond to the different parts of speech and sentence structures in your grammar. For example, you might define a pattern for matching nouns, a pattern for matching verbs, and a pattern for matching sentences that consist of a subject followed by a verb and an object.
To use these patterns for parsing, you would apply them to a text string using a regular expression engine, which would match the patterns to the appropriate parts of the string. The output of the parsing process would be a parse tree or other data structure that represents the grammatical structure of the sentence.
One limitation of regular expression parsing is that it is generally not suitable for handling more complex or ambiguous grammar. For example, it can be difficult to handle cases where a word could be either a noun or a verb depending on the context, or where the structure of a sentence is ambiguous.
We can also use regular expressions to break a larger text document into smaller chunks or tokens, based on specific patterns or delimiters.
To use regular expressions for text manipulation, you typically need to define a pattern that matches the text you want to find or manipulate. This pattern can include special characters and syntax to define the specific sequence of characters, numbers, or other elements that make up the text string.
For example, the regular expression pattern \d3-\d2-\d4 might be used to search for and extract Social Security numbers in a larger text document. This pattern matches a sequence of three digits, followed by a dash, then two more digits, another dash, and four final digits, which together represent the standard format for a Social Security number in the USA.
Once you have defined your regular expression pattern, you can use it with various text manipulation tools and programming languages, such as grep, sed, awk, Perl, Python, and many others, to perform complex text manipulation tasks.
Some programming languages, such as Perl and Python, have built-in support for regular expressions. Other programming languages, such as Java and C++, require you to use a library or API to work with regular expressions.
While regular expressions are powerful tools for text processing, they can also be complex and difficult to understand. It’s important to be familiar with the syntax and behavior of regular expressions to use them effectively in your code.
Tokenization
Section titled “Tokenization”A tokenizer is the first and in many ways the most essential component of a large language model pipeline. Its role is deceptively simple: convert raw, unstructured text into a standardized sequence of discrete tokens that can be mapped to integers and then embedded in a vector space suitable for neural computation. Yet, this step fundamentally shapes how the model perceives text, determines its vocabulary size, affects its computational requirements, and governs its robustness to previously unseen words or rare forms.
In the simplest possible strategy, the input is tokenized at the level of individual characters. This approach is theoretically elegant because it trivially guarantees complete coverage: every word in any language can be represented as a sequence of characters. If the model’s vocabulary consists of the 26 English letters, plus digits and punctuation, then any input can be tokenized without risk of out-of-vocabulary (OOV) errors. For example, the word “unbelievability” is simply split into:
[u,n,b,e,l,i,e,v,a,b,i,l,i,t,y]Formally, if C denotes the finite set of allowed characters, then the tokenizer is the mapping:
where
The advantage is that the embedding matrix is small because is only a few hundred symbols even for Unicode text. The disadvantage is severe: typical words span 5–15 characters, and entire sentences easily reach hundreds of tokens. Since a transformer’s self-attention mechanism has complexity in sequence length LLL, character tokenization dramatically raises the computational burden. Moreover, a single character carries almost no semantic information; the model must learn word boundaries and morphological structure purely from data, which demands greater depth, longer context windows, or more training time to match the fluency achievable with richer token units.
To overcome this, modern transformer models adopt subword tokenization schemes that split words into smaller units than whole words, but larger than single characters. The fundamental principle is that words are naturally compositional: stems, prefixes, suffixes, and inflections recur across the lexicon and can be reused to represent unseen words. Subword algorithms learn these recurring patterns in a purely data-driven way, balancing vocabulary size and sequence length.
Mathematically, a subword tokenizer learns a finite set Z and a segmentation rule:
with
Unlike characters, each subword can encode a morpheme, a whole frequent word, or a punctuation fragment.
One of the earliest and most enduring methods for learning subword units is Byte-Pair Encoding (BPE). BPE originates from data compression: it iteratively replaces the most frequent pair of symbols in a sequence with a new single symbol. In NLP, BPE is adapted by first initializing the vocabulary to contain all individual characters observed in the corpus. The corpus is then repeatedly scanned to find the most frequent pair of adjacent symbols (a,b). This pair is then merged into a new symbol:
The counts are updated, and the process repeats until a target vocabulary size is reached.
Formally, the BPE training step can be described as follows:

Each merge greedily increases the average length of subwords, capturing frequent patterns. For example, if “h” + “e” co-occur most often, they merge to “he”; then “he” + “r” might merge to “her”; eventually, “there” could become a single subword if it appears frequently.
At inference time, BPE tokenization is greedy: given a word, the longest available subword prefix in the vocabulary is matched and output; the remainder is then processed recursively. If no longer subword matches exist, the fallback is single characters, ensuring open vocabulary coverage.
An example clarifies this: suppose the final vocabulary contains “transform”, “er”, and “s”. Then the word “Transformers” would be split as:
[“Transform”,”er”,”s”]The Byte-Level BPE refinement, used in GPT-2, GPT-3, and GPT-4, generalizes BPE by applying it directly to bytes instead of Unicode characters. Here, the base vocabulary is exactly the set of all 256 possible byte values:
Any text, including emojis, diacritics, or corrupted strings, can be encoded losslessly as bytes. The same frequency-based merge procedure applies, learning which byte sequences should merge to form longer units. The advantage is that no character ever produces an OOV error. Moreover, GPT models store an explicit symbol for spaces (“Ġ”) to mark word boundaries: for example, “ GPT” becomes [ “ĠG”, “P”, “T” ].
The merge rule can be expressed mathematically as follows:

with
The corpus is updated after each merge, and the table of merges is fixed once training is complete.
A general pseudo-code for BPE (including byte-level BPE) is:
initialize V = set of bytes or charswhile |V| < target_vocab_size: count frequency of all adjacent pairs (x, y) select pair (x*, y*) with highest frequency merge (x*, y*) -> new token xy update corpus with xy replacing x yWordPiece, the method used by BERT, modifies this by replacing raw frequency maximization with a statistical likelihood objective. Instead of simply counting pairs, WordPiece measures how merging a pair improves the log-likelihood of the corpus under a simple unigram model. Denote by the corpus segmented according to the current vocabulary. The probability of the corpus is:

where is the current subword segmentation of word. The merge that yields the largest increase in this corpus probability is selected.
In practice, a simple approximation is used: the pair whose merged frequency divided by the product of its parts’ frequencies is highest:

This favors merges that capture statistically dependent pairs, rather than merely frequent pairs.
The WordPiece tokenizer also applies a continuation marker to preserve word boundary information: a subword like “##ing” indicates it cannot begin a word by itself but must attach to a preceding stem. This is crucial for the BERT model’s masked language modeling task, where understanding morphological structure helps predict masked tokens more accurately.
For example, with WordPiece, “unbelievable” may be tokenized as:
[ “un”, “##believ”, “##able” ].The model can learn embeddings for “believ” and “able” and generalize to “believability,” “believable,” and “unbelievably” without ever seeing each form in full.
All these algorithms share the same guarantee: given any input string, the tokenizer produces a finite sequence such that:
and
This is truly unknown; the only design constraint is the chosen balance between the vocabulary size and the maximum token sequence length. A larger vocabulary means more subwords and shorter sequences but a larger embedding table; a smaller vocabulary implies longer sequences and higher attention costs.
This is truly unknown; the only design constraint is the chosen balance between the vocabulary size and the maximum token sequence length. A larger vocabulary means more subwords and shorter sequences, but a larger embedding table; a smaller vocabulary implies longer sequences and higher attention costs.
In the context of computational scaling, one recalls that the self-attention module in transformers costs:
where and
A carefully chosen tokenizer minimizes while keeping manageable, a trade-off that explains why subword tokenization has become the universal practice for large-scale transformers.
In summary, character-level tokenization provides perfect coverage but at the expense of efficiency; word-level tokenization aligns well with human intuition but fails on unseen forms and inflates the parameter count. Subword tokenization methods—WordPiece, BPE, and byte-level BPE—strike the practical middle ground, discovering reusable linguistic units that reduce sparsity, enable robust generalization to unseen text, and ensure efficient training and inference at scale.
Explaining the preprocessing pipeline
Section titled “Explaining the preprocessing pipeline”In this section, the complete preprocessing pipeline that we provided in Figure 1.1 from Chapter 1 will be explained. As shown below, the input is a formatted text with encoded tags, similar to what we can extract from HTML web pages:
“<SUBJECT LINE> Employees details<END><BODY TEXT>Attached are 2 files,1st one is pairoll, 2nd is healtcare! New policy guidelines were issued, and the boarder police were informed<END>”Let’s examine the effect of applying each step to the text:
- Decode/remove encoding:
Employees details. Attached are 2 files, 1st one is pairoll, 2nd is healtcare! New policy guidelines were issued, and the boarder police were informed.
- Lowercasing:
employees details. attached are 2 files, 1st one is pairoll, 2nd is healtcare! new policy guidelines were issued, and the boarder police were informed.
- Digits to words:
employees details. attached are two files, first one is pairoll, second is healtcare! new policy guidelines were issued, and the boarder police were informed.
- Remove punctuation and other special characters:
employees details attached are two files first one is pairoll second is healtcare new policy guidelines were issued and the boarder police were informed
- Spelling corrections:
employees details attached are two files first one is payroll second is healthcare new policy guidelines were issued and the border police were informed
- Remove stop words:
employees details attached two files first one payroll second healthcare new policy guidelines issued border police informed
- Lemmatizing:
employee detail attached two file first one payroll second healthcare new policy guideline issued border police informed
- Stemming:
employe detail attach two file first one payrol second healthcar new polici guidelin issu border polic inform
With this, we have demonstrated how raw text moves through the full preprocessing pipeline, from encoded input to normalized token forms. Next, let’s review the code used to perform NER and POS tagging on the processed text.
Code for NER and POS
Section titled “Code for NER and POS”For this example, we used the spaCy library for Python to perform these tasks. Here our input is:
The companies that would be releasing their quarterly reports tomorrow are Microsoft, 4pm, Google, 4pm, and AT&T, 6pm.Here’s the output for NER:
The companies that would be releasing their quarterly reports tomorrow DATE are Microsoft ORG , 4pm TIME , Google ORG , 4pm TIME , and AT&T ORG , 6pm TIME .As you can see, using NER, we were able to detect parts of the sentence that are related to company names (ORG) or dates.
To make the linguistic annotations clearer, the following table presents the POS tags, NER labels, and dependency relations assigned by spaCy for each token in the sentence:
| Word | POS Tag | NER Tag | Dependency Relation |
|---|---|---|---|
| The | DET | — | det (modifier of companies) |
| companies | NOUN | — | nsubj (subject of “are”) |
| that | PRON | — | nsubj (subject of releasing) |
| would | AUX | — | aux (helper for releasing) |
| be | AUX | — | aux (helper for releasing) |
| releasing | VERB | — | relcl (relative clause for companies) |
| their | PRON | — | poss (possession of reports) |
| quarterly | ADJ | — | amod (modifier of “reports”) |
| reports | NOUN | — | dobj (direct object of “releasing”) |
| tomorrow | NOUN | DATE | npadvmod (adverbial modifier) |
| are | AUX | — | ROOT (main verb) |
| Microsoft | PROPN | ORG | attr (attribute of are) |
| 4 | NUM | TIME | nummod (modifier of noun) |
| pm | NOUN | TIME | appos (appositive of “Microsoft”) |
| PROPN | ORG | conj (conjunction with Microsoft) | |
| 4 | NUM | TIME | nummod (modifier of noun) |
| pm | NOUN | TIME | appos (appositive of Google) |
| and | CCONJ | — | cc (connector) |
| AT&T | PROPN | ORG | conj (conjunction with Microsoft) |
| 6 | NUM | TIME | nummod (modifier of pm) |
| pm | NOUN | TIME | appos (appositive of AT&T) |
Table 4.1 – POS, NER, and dependency parsing results using spaCy
Here’s the output:
[[‘companies’, ‘NOUN’], [‘releasing’, ‘VERB’], [‘quarterly’, ‘ADJ’], [‘reports’, ‘NOUN’], [‘tomorrow’, ‘NOUN’], [‘Microsoft’, ‘PROPN’], [‘pm’, ‘NOUN’], [‘Google’, ‘PROPN’], [‘pm’, ‘NOUN’], [‘AT&T’, ‘PROPN’], [‘pm’, ‘NOUN’]]POS tags depend on the underlying linguistic annotation scheme. For instance, spaCy may label “tomorrow” as a NOUN because it can function as a temporal noun phrase, even though it is often perceived as an adverb in common usage.
The preceding code examples exemplify the various aspects of preprocessing, which processes raw text and transforms it into a form that suits the downstream model and the purpose of the overall design.
Code for tokenizers
Section titled “Code for tokenizers”The code for the tokenizer is provided in the tokenizer.ipynb notebook on GitHub.
The provided Python script demonstrates how to construct Byte-Pair Encoding (BPE) and WordPiece tokenizers using the tokenizers library from Hugging Face. The code begins by defining a small sample corpus consisting of a few English sentences, which serves as the training data for both tokenization models. For the BPE tokenizer, a BPE model is instantiated along with a Whitespace pre-tokenizer, which segments text based on whitespace boundaries. A BpeTrainer is configured with a target vocabulary size and common special tokens, such as [UNK] and [CLS]. The tokenizer is then trained on the corpus, and a sample input is tokenized to illustrate the learned subword units.
Similarly, the WordPiece tokenizer follows the same structure: a WordPiece model is initialized with an unknown token, and a WordPieceTrainer is defined with matching vocabulary constraints and special tokens. The training procedure leverages the same corpus and pre-tokenizer to produce a subword vocabulary appropriate for tasks like language modeling and sequence classification. After training, the script outputs tokenized examples for both approaches and demonstrates how to serialize the tokenizers to JSON files for future use. This concise implementation highlights how BPE and WordPiece efficiently segment text into subword units, which helps balance vocabulary size and generalization in modern NLP applications.
Summary
Section titled “Summary”In this chapter, we covered a range of techniques and methods for text preprocessing, including normalization, tokenization, stop word removal, POS tagging, and more. We explored different approaches to these techniques, such as rule-based methods, statistical methods, and deep learning-based methods. We also discussed the advantages and disadvantages of each method, and provided examples and code snippets to illustrate their use.
At this point, you should have a solid understanding of the importance of text preprocessing and the various techniques and methods available for cleaning and preparing text data for analysis. You should be able to implement these techniques using popular libraries and frameworks in Python, and understand the trade-offs between different approaches. Furthermore, you should have a better understanding of how to process text data to achieve better results in NLP tasks, such as sentiment analysis, topic modeling, and text classification.
In the next chapter, we focus on empowering text classification using traditional machine learning techniques. We begin by outlining the technical requirements and common types of text classification tasks, followed by a detailed discussion of feature engineering approaches such as TF-IDF and Word2Vec embeddings, including the fundamentals of the Word2Vec model itself. We then examine model evaluation practices, challenges related to overfitting and underfitting, and strategies for effective hyperparameter tuning. The chapter also covers additional applied topics, including topic modeling and real-world machine learning system design, and concludes with a concise summary of key concepts and practical insights.
Questions
Section titled “Questions”- Why is text preprocessing a critical first step in NLP pipelines?
- What problem does lowercasing solve, and when might it be a bad idea?
- Why do we remove punctuation and special characters, and what is one common technique to do it?
- What is stop word removal, and what is its main benefit?
- What is the purpose of spell checking and correction in preprocessing?
- How do stemming and lemmatization differ, and what is a key tradeoff?
- What does a complete preprocessing pipeline look like in this chapter’s example, and why is the sequence useful?
- What is POS tagging and what are three broad approaches mentioned in the chapter?
References
Section titled “References”- Akbik, Alan, Duncan Blythe, and Roland Vollgraf. “Contextual String Embeddings for Sequence Labeling.” In Proceedings of the 27th International Conference on Computational Linguistics, 1638–1649, 2018.
- Devlin, Jacob, Ming-Wei Chang, Kenton Lee, and Kristina Toutanova. “BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding.” In Proceedings of the 2019 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, Volume 1 (Long and Short Papers), 4171–4186, 2019.
- Eisenstein, Jacob. Introduction to Natural Language Processing. Cambridge, MA: MIT Press, 2019.
- Gao, Jianfeng, Michel Galley, and Lihong Li. Neural Approaches to Conversational AI: Question Answering, Task-Oriented Dialogues and Social Chatbots. Foundations and Trends in Information Retrieval. Boston: Now Publishers, 2019.
- Jurafsky, Daniel, and James H. Martin. Speech and Language Processing: An Introduction to Natural Language Processing, Computational Linguistics, and Speech Recognition, with Language Models. 3rd ed. Stanford, CA: Stanford University, 2026. https://web.stanford.edu/~jurafsky/slp3/.
- Kudo, Taku, and John Richardson. “SentencePiece: A Simple and Language Independent Subword Tokenizer and Detokenizer for Neural Text Processing.” In Proceedings of the 2018 Conference on Empirical Methods in Natural Language Processing: System Demonstrations, 66–71, 2018.
- Lample, Guillaume, Miguel Ballesteros, Sandeep Subramanian, Kazuya Kawakami, and Chris Dyer. “Neural Architectures for Named Entity Recognition.” In Proceedings of the 2016 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, 260–270, 2016.
- Sennrich, Rico, Barry Haddow, and Alexandra Birch. “Neural Machine Translation of Rare Words with Subword Units.” In Proceedings of the 54th Annual Meeting of the Association for Computational Linguistics, Volume 1: Long Papers, 1715–1725, 2016.
- Wu, Yonghui, Mike Schuster, Zhifeng Chen, Quoc V. Le, Mohammad Norouzi, Wolfgang Macherey, et al. “Google’s Neural Machine Translation System: Bridging the Gap between Human and Machine Translation.” arXiv, September 2016. https://arxiv.org/abs/1609.08144