The Wayback Machine - https://web.archive.org/web/20240927045753/https://www.geeksforgeeks.org/tokenization-using-spacy-library/
Open In App

Tokenization Using Spacy library

Last Updated : 16 Sep, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Before moving to the explanation of tokenization, let’s first discuss what is Spacy. Spacy is a library that comes under NLP (Natural Language Processing). It is an object-oriented Library that is used to deal with pre-processing of text, and sentences, and to extract information from the text using modules and functions.

Tokenization is the process of splitting a text or a sentence into segments, which are called tokens. It is the first step of text preprocessing and is used as input for subsequent processes like text classification, lemmatization, etc.

Process followed to convert text into tokens

Process followed to convert text into tokens

Creating a blank language object gives a tokenizer and an empty pipeline to add modules in the pipeline along with a tokenizer we can use:

            

Intermediate steps for tokenization

Intermediate steps for tokenization

                              

Below is the Implementation

Python




# First we need to import spacy
import spacy
  
# Creating blank language object then
# tokenizing words of the sentence
nlp = spacy.blank("en")
  
doc = nlp("GeeksforGeeks is a one stop\
learning destination for geeks.")
  
for token in doc:
    print(token)


Output:

GeeksforGeeks
is
a
one
stop
learning
destination
for
geeks
.

We can also add functionality in tokens by adding other modules in the pipeline using spacy.load().

Python3




nlp = spacy.load("en_core_web_sm")
  
nlp.pipe_names


Output:

['tok2vec', 'tagger', 'parser', 'attribute_ruler', 'lemmatizer', 'ner']

Here is an example to show what other functionalities can be enhanced by adding modules to the pipeline.

Python




import spacy
  
# loading modules to the pipeline.
nlp = spacy.load("en_core_web_sm")
  
# Initialising doc with a sentence.
doc = nlp("If you want to be an excellent programmer \
, be consistent to practice daily on GFG.")
  
# Using properties of token i.e. Part of Speech and Lemmatization
for token in doc:
    print(token, " | ",
          spacy.explain(token.pos_),
          " | ", token.lemma_)


Output:

If  |  subordinating conjunction  |  if
you  |  pronoun  |  you
want  |  verb  |  want
to  |  particle  |  to
be  |  auxiliary  |  be
an  |  determiner  |  an
excellent  |  adjective  |  excellent
programmer  |  noun  |  programmer
,  |  punctuation  |  ,
be  |  auxiliary  |  be
consistent  |  adjective  |  consistent
to  |  particle  |  to
practice  |  verb  |  practice
daily  |  adverb  |  daily
on  |  adposition  |  on
GFG  |  proper noun  |  GFG
.  |  punctuation  |  .

In the above example, we have used part of speech (POS) and lemmatization using NLP modules, which resulted in POS for every word and lemmatization (a process to reduce every token to its base form). We were not able to access this functionality before, this functionality is only added after we loaded our NLP instance with (“en_core_web_sm”). 



Similar Reads

RSA Algorithm using Multiple Precision Arithmetic Library
Public Key Cryptography is also known as Asymmetric Cryptography is the type of cryptography which involves the usage of two keys namely Public Key and Private Key. The Public Key of the receiver is used to encrypt the plaintext by the sender while the Private Key of the receiver is used to decrypt the encrypted message and hence can be decrypted o
4 min read
Information Technology Infrastructure Library (ITIL)
Information Technology Infrastructure Library (ITIL) is provided with a framework of best practices for delivering IT services. The ITIL is an appropriate method to management of IT service and also management can help businesses manage risk, strengthen customer relations, establish cost-effective practices, and build a stable IT environment that p
3 min read
How to Use Picasso Image Loader Library in Android?
Picasso is open source and one of the widely used image download libraries in Android. It is created and maintained by Square. It is among the powerful image download and caching library for Android. Picasso simplifies the process of loading images from external URLs and displays them on your application. For example, downloading an image from the
6 min read
Software Framework vs Library
Many of us will be unaware of this difference which is really important to understand during development. The possible answer to this question, if asked, will be "Framework is a collection of various libraries". However, this definition is not entirely true. "Who calls whom" i.e. the caller/callee relationship defines the difference between the two
4 min read
C Library math.h Functions
The math.h header defines various C mathematical functions and one macro. All the functions available in this library take double as an argument and return double as the result. Let us discuss some important C math functions one by one. C Math Functions1. double ceil (double x) The C library function double ceil (double x) returns the smallest inte
6 min read
How to Use Glide Image Loader Library in Android Apps?
Glide, like Picasso, can load and display images from many sources, while also taking care of caching and keeping a low memory impact when doing image manipulations. Official Google apps (like the app for Google I/O 2015) are using Glide. In this article, we're going to explore the functionalities of Glide and why it's superior in certain aspects.
4 min read
<strings> library in C++ STL
Member functions String.constructor : Construct string object (public member function ).String.destructor : String destructor (public member function )String.operator= : String assignment (public member function ) Iterators Begin : Return iterator to beginning (public member function )End : Return iterator to end (public member function )Advance :
3 min read
Containers in C++ STL (Standard Template Library)
A container is a holder object that stores a collection of other objects (its elements). They are implemented as class templates, which allows great flexibility in the types supported as elements. The container manages the storage space for its elements and provides member functions to access them, either directly or through iterators (reference ob
2 min read
<numeric> library in C++ STL
Common mathematical functions std::fabs: This function returns the absolute value. std::sqrt: This function returns the square root std::sin: This function returns the sine measured in radians. Special mathematical functions std::beta: This function evaluates the (complete) Beta integral with given parameters std::hermite: This function Returns the
2 min read
<regex> library in C++ STL
Main classes These classes encapsulate a regular expression and the results of matching a regular expression within a target sequence of characters. basic_regex: Regular expression object (class template) sub_match: Identifies the sequence of characters matched by a sub-expression (class template) match_results: Identifies one regular expression ma
2 min read
Decimal to Binary using recursion and without using power operator
Given an integer N, the task is convert and print the binary equaiva;ent of N.Examples: Input: N = 13 Output: 1101Input: N = 15 Output: 1111 Approach Write a recursive function that takes an argument N and recursively calls itself with the value N / 2 as the new argument and prints N % 2 after the call. The base condition will be when N = 0, simply
3 min read
Largest in array without using conditionals / bitwise / ternary operators
Define a function int max(int a[], int n) which returns the largest integer from an integer array consisting of n elements (without using conditionals / bitwise / ternary operators / library function to find largest Examples: Input : arr[] = {16, 14, 15, 17, 9} Output : 17 Input : arr[] = {10, 13, 11, 13} Output : 13 The idea is similar to Maximum
4 min read
Count the number of objects using Static member function
Prerequisite : Static variables , Static Functions Write a program to design a class having static member function named showcount() which has the property of displaying the number of objects created of the class. Explanation: In this program we are simply explaining the approach of static member function. We can define class members and member fun
2 min read
Find nth Fibonacci number using Golden ratio
Fibonacci series = 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ........Different methods to find nth Fibonacci number are already discussed. Another simple way of finding nth Fibonacci number is using golden ratio as Fibonacci numbers maintain approximate golden ratio till infinite. Golden ratio: [Tex]\varphi ={\frac {1+{\sqrt {5}}}{2}}=1.6180339887\ldots [/T
6 min read
Message encryption and decryption using UDP server
The process of message encryption and decryption during client-server communication using UDP server is as follows: The client requests the server with a file name.The corresponding file is opened by the server and sends the file using datagram socket.The sender sends the encrypted text (Xoring) with a fixed length key.The receiver receives the enc
3 min read
SQL using Python and SQLite | Set 2
Databases offer numerous functionalities by which one can manage large amounts of information easily over the web, and high-volume data input and output over a typical file such as a text file. SQL is a query language and is very popular in databases. Many websites use MySQL. SQLite is a "light" version that works over syntax very much similar to S
3 min read
Python implementation of automatic Tic Tac Toe game using random number
Tic-tac-toe is a very popular game, so let's implement an automatic Tic-tac-toe game using Python. The game is automatically played by the program and hence, no user input is needed. Still, developing an automatic game will be lots of fun. Let's see how to do this. NumPy and random Python libraries are used to build this game. Instead of asking the
5 min read
Reverse a string in C/C++ using Client Server model
This article describes a Client and Server setup where a Client connects, sends a string to server and the server shows the original string and sends reversed string to client using socket connection. Prerequisite : Socket Programming Examples: Input : welcome Output :emoclew Input :geeks for geeks Output :skeeg rof skeeg Explanation In this, first
3 min read
Extracting email addresses using regular expressions in Python
Let suppose a situation in which you have to read some specific data like phone numbers, email addresses, dates, a collection of words etc. How can you do this in a very efficient manner?The Best way to do this by Regular Expression. Let take an example in which we have to find out only email from the given input by Regular Expression. Examples: In
3 min read
Leaf nodes from Preorder of a Binary Search Tree (Using Recursion)
Given Preorder traversal of a Binary Search Tree. Then the task is to print leaf nodes of the Binary Search Tree from the given preorder. Examples : Input : preorder[] = {890, 325, 290, 530, 965}; Output : 290 530 965 Tree represented is, 890 / \ 325 965 / \ 290 530 Input : preorder[] = { 3, 2, 4 }; Output : 2 4 In this post, a simple recursive sol
5 min read
Print Binary Tree levels in sorted order | Set 2 (Using set)
Given a tree, print the level order traversal in sorted order. Examples : Input : 7 / \ 6 5 / \ / \ 4 3 2 1 Output : 7 5 6 1 2 3 4 Input : 7 / \ 16 1 / \ 4 13 Output : 7 1 16 4 13 We have discussed a priority queue based solution in below post.Print Binary Tree levels in sorted order | Set 1 (Using Priority Queue) In this post, a set (which is impl
5 min read
Print 1 2 3 infinitely using threads in C
Print 1 2 3 infinitely using thread. Create three threads viz T1, T2, and T3 such that those should print 1 2 3 sequence infinitely. Examples : Output :1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 ...... Prerequisite : Threads in C Approach : Start an infinite loop and initialize a variable 'done' to 1. Now, check for the value of done is not equal to 1. If it is
2 min read
Paths to travel each nodes using each edge (Seven Bridges of Königsberg)
There are n nodes and m bridges in between these nodes. Print the possible path through each node using each edges (if possible), traveling through each edges only once. Examples : Input : [[0, 1, 0, 0, 1], [1, 0, 1, 1, 0], [0, 1, 0, 1, 0], [0, 1, 1, 0, 0], [1, 0, 0, 0, 0]] Output : 5 -> 1 -> 2 -> 4 -> 3 -> 2 Input : [[0, 1, 0, 1, 1]
15+ min read
Communication between two process using signals in C
Prerequisite : C signal handling In this post, the communication between child and parent processes is done using kill() and signal(), fork() system call. fork() creates the child process from the parent. The pid can be checked to decide whether it is the child (if pid == 0) or the parent (pid = child process id).The parent can then send messages t
3 min read
Large number arithmetic using doubly linked list
Given two very large numbers in form of strings. Your task is to apply different arithmetic operations on these strings. Prerequisite : Doubly Linked List. Examples: Input : m : 123456789123456789123456789123456789123456789123456789 n : 456789123456789123456789123456789123456789123456789 Output : Product : 563937184884934839205932493526930147847927
13 min read
Fetching top news using News API
News API is a simple JSON-based REST API for searching and retrieving news articles from all over the web. Using this, one can fetch the top stories running on a news website or can search top news on a specific topic (or keyword). News can be retrieved based on some criteria. Say the topic (keyword) to be searched is 'Geeksforgeeks' or might be co
5 min read
Reverse Morris traversal using Threaded Binary Tree
What is Morris traversal?Morris (InOrder) Traversal is a tree traversal algorithm that does not use recursion or stacks. This traversal creates links as descendants and outputs nodes using those links. Finally, undo the changes to restore the original tree.Given a binary tree, task is to do reverse inorder traversal using Morris Traversal. Prerequi
10 min read
Java | Date format validation using Regex
We use java.util.regex.Pattern.compile(String regex) method which compiles the given regular expression into a pattern. Here regex is the expression to be compiled. // Java program to check if given date is // valid or not. import java.util.regex.Matcher; import java.util.regex.Pattern; public class GeeksforGeeks { // Returns true if d is in format
1 min read
Removing whitespaces using Regex in Java
Given a string, your task is to remove the whitespaces in the string using Java Regex (Regular Expressions). Examples Input : Hello Everyone . Output : HelloEveryone. Input : Geeks for Geeks . Output : GeeksforGeeks.Regular Expressions Regular Expressions or Regex is an API for defining String patterns that can be used for searching, manipulating,
3 min read
Using Variables in JShell of Java 9
Prerequisite : JShell in Java 9 We can declare variables and use anywhere throughout Jshell session. Let's create an integer variable. Semicolon (;) is optional, we can leave it and it works fine. See, variable b is created without using semicolon. Scratch Variables If we don't provide variable name, Java create implicit variable to store the value
1 min read
Article Tags :
Practice Tags :