The Wayback Machine - https://web.archive.org/web/20241001010304/https://www.geeksforgeeks.org/rule-based-tokenization-in-nlp/
Open In App

Rule-Based Tokenization in NLP

Last Updated : 04 Jun, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Natural Language Processing (NLP) is a subfield of artificial intelligence that aims to enable computers to process, understand, and generate human language. One of the critical tasks in NLP is tokenization, which is the process of splitting text into smaller meaningful units, known as tokens. Dictionary-based tokenization is a common method used in NLP to segment text into tokens based on a pre-defined dictionary.

Tokenization is the process of splitting text into individual tokens, usually words or sentences and separating them from one another using spaces or punctuation or some specific rules. In rule-based tokenization, a set of rules is defined to determine how text is split into tokens. These rules can be based on various factors such as whitespace, punctuation, and context.

Rule-Based Tokenization:

Rule-based tokenization is a technique where a set of rules is applied to the input text to split it into tokens. These rules can be based on different criteria, such as whitespace, punctuation, regular expressions, or language-specific rules. Here are some common concepts related to rule-based tokenization:

Whitespace tokenization

This approach splits the input text based on whitespace characters such as space, tab, or newline. 

For example, the sentence : "This is a sample text." 
would be split into the following tokens: "This", "is", "a", "sample", and "text."

The following Python code demonstrates whitespace rule-based tokenization:

Steps for Rule-Based Tokenization:

  • Load the input text: The input text can be loaded from a file or entered by the user.
  • Define the tokenization rules: Based on the type of tokenization required, define the rules to split the input text into tokens. These rules can be based on whitespace, punctuation, regular expressions, or language-specific rules.
  • Apply the rules to the input text: Use the defined rules to split the input text into tokens.
  • Output the tokens: Output the tokens generated by the tokenization process.

Python3




# Step 1: Load the input text
text = "The quick brown fox jumps over the lazy dog."
  
# Step 2: Define the tokenization rules (split on whitespace)
tokens = text.split()
  
# Step 4: Output the tokens
print(tokens)


Output:

['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog.']

Regular expression tokenization

This approach uses regular expressions to split the input text based on a pattern. This is mainly used when we have to find some specific type of patterns in text like email id, phone number, order id, currency, etc.

For example, the regular expression "[\w]+-[\w]+-[\w]+" will match the "Geeks-for-Geeks" 
and ([\w\.-]+@[\w]+.[\w]+) will match the email id. from
"Hello, I am working at Geeks-for-Geeks and my email is pawan.gunjan123@geeksforgeeks.com." 

The following Python code demonstrates whitespace Regular expression tokenization:

Python3




import re
  
#Load the input text
text = "Hello, I am working at Geeks-for-Geeks and my email is pawangunjan23@geeksforgeeks.com."
  
#Define the regular expression pattern
p='([\w]+-[\w]+-[\w]+)|([\w\.-]+@[\w]+.[\w]+)'
  
# Find matches
matches = re.findall(p, text)
# print output
for match in matches:
    if match[0]:
        print(f"Company Name: {match[0]}")
    else:
        print(f"Email address: {match[1]}")


Output:

Company Name: Geeks-for-Geeks
Email address: pawan.gunjan123@geeksforgeeks.com

Punctuation tokenization

This approach splits the input text based on punctuation characters such as period, comma, or semicolon. 

For example, the sentence "Hello Geeks! How can I help you?" 
would be split into the following tokens: 'Hello', 'Geeks', 'How', 'can', 'I', 'help', 'you'

The following Python code demonstrates punctuation rule-based tokenization:

Python3




import re
  
# Load the input text
text = "Hello Geeks! How can I help you?"
  
# Define the regular expression pattern
# Matches one or more non-alphanumeric characters
pattern = r'\W+' 
  
# Remove the punctuation and get the resulting string
result = re.sub(pattern, ' ', text)
  
# tokenize
tokens = re.findall(r'\b\w+\b|[^\w\s]', result)
  
# Print the result
print(tokens)


Output:

['Hello', 'Geeks', 'How', 'can', 'I', 'help', 'you']

Language-specific tokenization

This approach uses language-specific rules to split the input text into tokens. For example, in some languages, words can be concatenated without spaces, such as in German. Therefore, language-specific rules are needed to split the input text into meaningful tokens.

Python3




from inltk.inltk import tokenize
from inltk.inltk import setup
setup('sa')
  
Text = "'āĨ āĪ­āĨ‚āΰāĨāĪ­āĪĩ: āĪļāĨāĪĩ: āĪĪāĪĪāĨāĪļāĪĩāĪŋāĪĪāĨāΰāĨāĪĩāΰāĨ‡āĪĢāĨāĪŊāĪ‚ āĪ­āΰāĨāĪ—āĨ‹ āĪĶāĨ‡āĪĩāĪļāĨāĪŊ āΧāĨ€āĪŪāĪđāĪŋ āΧāĪŋāĪŊāĨ‹ āĪŊāĨ‹ āĪĻ: āĪŠāĨāΰāΚāĨ‹āĪĶāĪŊāĪūāĪĪāĨāĨĪ'"
# tokenize(input text, language code)
tokenize(Text, "sa")


Output:

["▁'",
 'āĨ',
 '▁āĪ­āĨ‚',
 'āΰāĨ',
 'āĪ­āĪĩ',
 ':',
 '▁āĪļāĨāĪĩ',
 ':',
 '▁āĪĪāĪĪāĨ',
 'āĪļ',
 'āĪĩāĪŋ',
 'āĪĪāĨ',
 'āΰāĨ',
 'āĪĩāΰāĨ‡āĪĢāĨāĪŊ',
 'āĪ‚',
 '▁āĪ­',
 'āΰāĨāĪ—',
 'āĨ‹',
 '▁āĪĶāĨ‡āĪĩāĪļāĨāĪŊ',
 '▁āΧāĨ€āĪŪ',
 'āĪđāĪŋ',
 '▁',
 'āΧāĪŋ',
 'āĪŊāĨ‹',
 '▁āĪŊāĨ‹',
 '▁āĪĻ',
 ':',
 '▁āĪŠāĨāΰ',
 'āΚ',
 'āĨ‹āĪĶāĪŊ',
 'āĪūāĪĪāĨ',
 "āĨĪ'"]


Similar Reads

Dictionary Based Tokenization in NLP
Natural Language Processing (NLP) is a subfield of artificial intelligence that aims to enable computers to process, understand, and generate human language. One of the critical tasks in NLP is tokenization, which is the process of splitting text into smaller meaningful units, known as tokens. Dictionary-based tokenization is a common method used i
5 min read
Subword Tokenization in NLP
Subword Tokenization is a Natural Language Processing technique(NLP) in which a word is split into subwords and these subwords are known as tokens. This technique is used in any NLP task where a model needs to maintain a large vocabulary and complex word structures. The concept behind this, frequently occurring words should be in the vocabulary whe
5 min read
What is Tokenization in Natural Language Processing (NLP)?
Tokenization is a fundamental process in Natural Language Processing (NLP), essential for preparing text data for various analytical and computational tasks. In NLP, tokenization involves breaking down a piece of text into smaller, meaningful units called tokens. These tokens can be words, subwords, or even characters, depending on the specific nee
5 min read
Rule Based Approach in NLP
Natural Language Processing serves as an interrelationship between human language and computers. It is a subfield of Artificial Intelligence that helps machines process, understand and generate natural language intuitively. Common tasks done by NLP are text and speech processing, language translation, sentiment analysis, etc. The use cases include
7 min read
What is Tokenization?
Tokenization is a fundamental process in Natural Language Processing (NLP) that involves breaking down a stream of text into smaller units called tokens. These tokens can range from individual characters to full words or phrases, depending on the level of granularity required. By converting text into these manageable chunks, machines can more effec
5 min read
Tokenization with the SentencePiece Python Library
Tokenization is a crucial step in Natural Language Processing (NLP), where text is divided into smaller units, such as words or subwords, that can be further processed by machine learning models. One of the most popular tools for tokenization is the SentencePiece library, developed by Google. This versatile tool is designed to handle various text p
5 min read
NLP | Classifier-based Chunking | Set 2
Using the data from the treebank_chunk corpus let us evaluate the chunkers (prepared in the previous article). Code #1 : C/C++ Code # loading libraries from chunkers import ClassifierChunker from nltk.corpus import treebank_chunk train_data = treebank_chunk.chunked_sents()[:3000] test_data = treebank_chunk.chunked_sents()[3000:] # initializing chun
2 min read
NLP | Classifier-based tagging
ClassifierBasedPOSTagger class: It is a subclass of ClassifierBasedTagger that uses classification technique to do part-of-speech tagging. From the words, features are extracted and then passed to an internal classifier. It classifies the features and returns a label i.e. a part-of-speech tag. The feature detector finds multiple length suffixes, do
2 min read
NLP | Training Tagger Based Chunker | Set 1
To train a chunker is an alternative to manually specifying regular expression (regex) chunk patterns. But manually training to specify the expression is a tedious task to do as it follows the hit and trial method to get the exact right patterns. So, existing corpus data can be used to train chunkers. In the codes below, we are using treebank_chunk
2 min read
NLP | Training Tagger Based Chunker | Set 2
Conll2000 corpus defines the chunks using IOB tags. It specifies where the chunk begins and ends, along with its types.A part-of-speech tagger can be trained on these IOB tags to further power a ChunkerI subclass.First using the chunked_sents() method of corpus, a tree is obtained and is then transformed to a format usable by a part-of-speech tagge
3 min read
NLP | Classifier-based Chunking | Set 1
The ClassifierBasedTagger class learns from the features, unlike most part-of-speech taggers. ClassifierChunker class can be created such that it can learn from both the words and part-of-speech tags, instead of just from the part-of-speech tags as the TagChunker class does. The (word, pos, iob) 3-tuples is converted into ((word, pos), iob) 2-tuple
2 min read
5 Benefits of Using NLP Based Chatbot
With the growing pace of technology, companies are now looking for better and more innovative ways to serve their customers. For the past few years, we’ll have been hearing about chat support systems provided by different companies in different domains. Be it food delivery, E-commerce, or Ticket booking, chatbots are almost everywhere now and they
6 min read
LSTM Based Poetry Generation Using NLP in Python
One of the major tasks that one aims to accomplish in Conversational AI is Natural Language Generation (NLG) which refers to employing models for the generation of natural language. In this article, we will get our hands on NLG by building an LSTM-based poetry generator. Note: The readers of this article are expected to be familiar with LSTM. In or
7 min read
Rule-Based Classifier - Machine Learning
Rule-based classifiers are just another type of classifier which makes the class decision depending by using various "if..else" rules. These rules are easily interpretable and thus these classifiers are generally used to generate descriptive models. The condition used with "if" is called the antecedent and the predicted class of each rule is called
4 min read
Rule Based System Vs Machine Learning System
There are two main approaches in Artificial intelligence they are rule-based systems and machine-learning systems. Rule-based systems follow explicit rules created by human experts. They're like a set of instructions given to a computer that follows to make decisions. These systems are good for problems with clear rules and paths. On the other hand
8 min read
Forward Chaining and Backward Chaining inference in Rule-Based Systems
Rule-based systems are a cornerstone of artificial intelligence, enabling machines to make decisions based on a set of predefined rules. These systems utilize logical inferences to derive conclusions from given data. Two primary methods of inference in rule-based systems are forward chaining and backward chaining. This article explores the mechanis
5 min read
Building a Rule-Based Chatbot with Natural Language Processing
In the evolving field of Artificial Intelligence, chatbots stand out as both accessible and practical tools. Specifically, rule-based chatbots, enriched with Natural Language Processing (NLP) techniques, provide a robust solution for handling customer queries efficiently. This article explores the essential prerequisites, tools, and methods for con
7 min read
Rule-Based System in AI
Rule-based systems, a foundational technology in artificial intelligence (AI), have long been instrumental in decision-making and problem-solving across various domains. These systems operate on a set of predefined rules and logic to make decisions, perform tasks, or derive conclusions. Despite the rise of more advanced AI methodologies, such as ma
7 min read
What is the difference between word-based and char-based text generation RNNs?
Answer: Word-based RNNs generate text based on words as units, while char-based RNNs use characters as units for text generation.Word-based RNNs emphasizing semantic meaning and higher-level structures, while char-based RNNs excel in capturing finer character-level patterns. AspectWord-based RNNsChar-based RNNsUnit of ProcessingOperates on words as
2 min read
BART Model for Text Auto Completion in NLP
BART stands for Bidirectional and Auto-Regressive Transformer. It is a denoising autoencoder that is a pre-trained sequence-to-sequence method, that uses masked language modeling for Natural Language Generation and Translation. It is developed by Lewis et al. in 2019. BART architecture is similar to an encoder-decoder network except that it uses a
7 min read
Processing text using NLP | Basics
In this article, we will be learning the steps followed to process the text data before using it to train the actual Machine Learning Model. Importing Libraries The following must be installed in the current working environment: NLTK Library: The NLTK library is a collection of libraries and programs written for processing of English language writt
2 min read
Readability Index in Python(NLP)
Readability is the ease with which a reader can understand a written text. In natural language, the readability of text depends on its content (the complexity of its vocabulary and syntax). It focuses on the words we choose, and how we put them into sentences and paragraphs for the readers to comprehend. Our main objective in writing is to pass alo
6 min read
Feature Extraction Techniques - NLP
Introduction : This article focuses on basic feature extraction techniques in NLP to analyse the similarities between pieces of text. Natural Language Processing (NLP) is a branch of computer science and machine learning that deals with training computers to process a large amount of human (natural) language data. Briefly, NLP is the ability of com
11 min read
Bidirectional LSTM in NLP
In this article, we will first discuss bidirectional LSTMs and their architecture. We will then look into the implementation of a review system using Bidirectional LSTM. Finally, we will conclude this article while discussing the applications of bidirectional LSTM. Bidirectional LSTM (BiLSTM)Bidirectional LSTM or BiLSTM is a term used for a sequenc
8 min read
NLP | Chunking and chinking with RegEx
Chunk extraction or partial parsing is a process of meaningful extracting short phrases from the sentence (tagged with Part-of-Speech). Chunks are made up of words and the kinds of words are defined using the part-of-speech tags. One can even define a pattern or words that can't be a part of chuck and such words are known as chinks. A ChunkRule cla
2 min read
NLP | Training Unigram Tagger
A single token is referred to as a Unigram, for example - hello; movie; coding. This article is focused on unigram tagger. Unigram Tagger: For determining the Part of Speech tag, it only uses a single word. UnigramTagger inherits from NgramTagger, which is a subclass of ContextTagger, which inherits from SequentialBackoffTagger. So, UnigramTagger i
2 min read
NLP | Synsets for a word in WordNet
WordNet is the lexical database i.e. dictionary for the English language, specifically designed for natural language processing. Synset is a special kind of a simple interface that is present in NLTK to look up words in WordNet. Synset instances are the groupings of synonymous words that express the same concept. Some of the words have only one Syn
2 min read
NLP | Word Collocations
Collocations are two or more words that tend to appear frequently together, for example - United States. There are many other words that can come after United, such as the United Kingdom and United Airlines. As with many aspects of natural language processing, context is very important. And for collocations, context is everything. In the case of co
3 min read
NLP | WuPalmer - WordNet Similarity
How does Wu & Palmer Similarity work? It calculates relatedness by considering the depths of the two synsets in the WordNet taxonomies, along with the depth of the LCS (Least Common Subsumer). The score can be 0 < score <= 1. The score can never be zero because the depth of the LCS is never zero (the depth of the root of taxonomy is one).
2 min read
NLP | Splitting and Merging Chunks
SplitRule class : It splits a chunk based on the specified split pattern for the purpose. It is specified like <NN.*>}{<.*> i.e. two opposing curly braces surrounded by a pattern on either side. MergeRule class : It merges two chunks together based on the ending of the first chunk and the beginning of the second chunk. It is specified l
2 min read