NLP libraries: NLTK, spaCy, TextBlob and Gensim
Practical study notes comparing NLTK, spaCy, TextBlob and Gensim: what each library is for, exact definitions, API syntax to remember, two runnable Python examples, common exam mistakes and sample exam question types.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Libraries make common NLP work simple so engineers can build or prototype text systems quickly. NLTK, spaCy, TextBlob and Gensim are the tools you will use for tasks such as tokenisation, stemming/lemmatisation, POS tagging, named-entity recognition (NER), and topic modelling — common components in search engines, chatbots, text analytics and information retrieval systems.
Key ideas
Note: I define each term before using it.
Natural-language processing (NLP) — the field of computer science that gives machines the ability to read, understand and generate human language. (I will refer to other topics such as Tokenisation, POS tagging, Topic modelling etc. by name rather than re-teaching them.)
Library — reusable code packaged with APIs (functions/classes) that implements common algorithms so an engineer does not rewrite them.
NLTK (Natural Language Toolkit) — a Python library for teaching and research in NLP. It contains many algorithms (tokenisers, stemmers, corpus readers, classification) and example corpora. Exact: NLTK is a toolkit, not a single pipeline implementation; you pick components and wire them.
spaCy — an industrial-grade Python library focused on fast, accurate pipelines for tokenisation, POS tagging, dependency parsing and NER. spaCy provides an integrated pipeline object you can load as a model (for example
en_core_web_sm) and run on text to get tokens+annotations in one pass.TextBlob — a high-level Python library built on NLTK and Pattern (when available). It exposes simple APIs for common tasks (noun phrases, sentiment, translation wrappers). Exact: TextBlob aims for ease-of-use, not maximum control.
Gensim — a Python library for vector-space modelling, topic modelling and similarity retrieval on corpora using memory-efficient, incremental (streaming) algorithms (e.g., LDA, word2vec, doc2vec). Exact: Gensim works with tokenised documents and builds dictionaries and bag-of-words (BoW) representations.
Tokenisation — definition: splitting raw text into atomic units called tokens (words, punctuation). Example: "India is big." -> tokens: ["India","is","big","."]
Stemming — definition: crude algorithmic reduction of words to a word-stem (not guaranteed to be a valid word). Example: Porter stemmer may map "running" -> "run" (approximate).
Lemmatisation — definition: reduction of a word to its lemma (dictionary form) using morphosyntactic analysis (requires POS). Example: "better" -> "good" when correct POS and rules applied.
Bag-of-words (BoW) — definition: represent a document as counts of tokens (order ignored). To build BoW: (1) create a dictionary mapping token->id, (2) convert each document to list of (token_id, count).
Vector-space model / TF-IDF — definition: transform BoW counts to weighted vectors where weights down-weight common tokens across the corpus. Used for retrieval and clustering.
Typical mapping of tasks to libraries (draw this pipeline as explained below): tokenisation and teaching examples -> NLTK; production pipelines with fast parsing and NER -> spaCy; quick prototypes and sentiment or translation wrappers -> TextBlob; topic modelling and similarity search -> Gensim.
Diagram to draw (exam answers often need a diagram):
- Draw 6 boxes horizontally, left to right, labelled: "Raw text" -> "Tokenisation" -> "Normalisation (lowercase, stopwords, stemming/lemmatisation)" -> "Syntactic analysis (POS, parsing, NER)" -> "Vectorisation (BoW, TF-IDF, embeddings)" -> "Modelling / Applications (classification, topic models, retrieval)".
- Under the Tokenisation box write: "NLTK.tokenize, spaCy.tokenizer". Under Normalisation write "NLTK.stem/lemmatize, spaCy token.lemma_". Under Syntactic write "spaCy token.tag_ and token.dep_, NLTK.parsers". Under Vectorisation write "Gensim.Dictionary, Gensim.TfidfModel". Under Applications write examples: "TextBlob.sentiment, Gensim.LdaModel, custom classifier".
Assumptions and limitations (exact statements):
- NLTK provides algorithms but not a single production pipeline; you must assemble components; it requires occasional corpus downloads for some features. (Assumption: user can install packages and optionally download corpora.)
- spaCy provides pre-trained statistical models; accuracy and token/label outputs depend on the model (size and version). (Assumption: model such as
en_core_web_smis installed.) - Gensim expects pre-tokenised input and streams data for large corpora; it does not do tokenisation or extensive text normalisation for you.
Formulas
(For a programming topic we list the syntax to remember; each on its own line as required.)
from nltk.stem import PorterStemmer — import Porter stemmer from NLTK
ps = PorterStemmer() — create Porter stemmer object
ps.stem(token) — stem token using Porter
import spacy — import spaCy
nlp = spacy.load('en_core_web_sm') — load spaCy model (must be installed)
doc = nlp(text) — run spaCy pipeline on text to get tokens and annotations
from gensim.corpora import Dictionary — import Gensim dictionary
dictionary = Dictionary(list_of_token_lists) — build token->id map
bow = dictionary.doc2bow(token_list) — convert token list to bag-of-words list (token_id, count)
from gensim.models import TfidfModel — import TF-IDF model
tfidf = TfidfModel(corpus_bow) — build TF-IDF model from BoW corpus
tfidf[bow_doc] — transform a single BoW document to TF-IDF weights
from textblob import TextBlob — import TextBlob
blob = TextBlob(text) — create TextBlob object
blob.sentiment — get sentiment polarity & subjectivity (requires Pattern or fallback)
Worked examples
Example 1 — simple rule-based stemmer (Python, runs without downloads) Program (copy and run in any Python 3 environment):
# simple_stemmer.py
def simple_stem(word):
w = word.lower()
if len(w) > 4 and w.endswith('ing'):
return w[:-3]
if len(w) > 3 and w.endswith('ed'):
return w[:-2]
if len(w) > 3 and w.endswith('es'):
return w[:-2]
if len(w) > 2 and w.endswith('s'):
return w[:-1]
return w
text = "Studying runs classes buses watched"
tokens = [t.strip('.,!') for t in text.split()]
stems = [simple_stem(t) for t in tokens]
print('Tokens:', tokens)
print('Stems :', stems)
Sample input (the program contains the input string) and exact output: Tokens: ['Studying', 'runs', 'classes', 'buses', 'watched'] Stems : ['study', 'run', 'class', 'bus', 'watch']
Notes: this example shows a simple algorithmic stemmer — it is not linguistically accurate, but it is deterministic and helps understand what "stemming" means.
Example 2 — Gensim: build Dictionary and BoW representations (Python; requires gensim installed) Program (copy and run):
# gensim_bow_example.py
from gensim.corpora import Dictionary
texts = [
['human', 'interface', 'computer'],
['survey', 'user', 'computer', 'system', 'response', 'time'],
['eps', 'user', 'interface', 'system']
]
dictionary = Dictionary(texts)
print(dictionary.token2id)
corpus_bow = [dictionary.doc2bow(text) for text in texts]
print(corpus_bow)
Sample input: the token lists are inside the program. Exact output (deterministic): {'human': 0, 'interface': 1, 'computer': 2, 'survey': 3, 'user': 4, 'system': 5, 'response': 6, 'time': 7, 'eps': 8} [[(0, 1), (1, 1), (2, 1)], [(2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 1)], [(1, 1), (4, 1), (5, 1), (8, 1)]]
Example 3 — model answer (theory) — short exam question: "Compare NLTK and spaCy and say when you would use each." (Model answer)
- NLTK: best for teaching, algorithm-level study and small experiments because it contains many implementations and corpora. It is flexible but not optimised as a single pipeline. Use NLTK when you need to learn algorithms, experiments, or custom rule-based processing.
- spaCy: designed for production; it gives a single pipeline (tokenizer->tagger->parser->ner) and is optimised for speed and ease of use. Use spaCy for building real-time applications (chatbots, pipelines) where you want reliable pre-trained models. A full answer states these differences, gives an example scenario for each, and mentions installation / model requirements for spaCy.
Common mistakes
- Assuming spaCy and NLTK tokens will match exactly (they use different tokeniser rules).
- Trying to call spaCy model without installing it (you must run
python -m spacy download en_core_web_sm). - Using stemming when lemmatisation is required (stems are not dictionary words; many exam questions ask to justify choice).
- For Gensim: forgetting that it expects tokenised text (strings split into lists of tokens). Passing raw strings silently produces wrong results.
For your exam
Kinds of questions this topic produces:
- Definitions: define tokenisation, stemming, lemmatisation, BoW, TF-IDF, topic model, and name a library best suited for each.
- Short notes: compare NLTK vs spaCy vs Gensim vs TextBlob; list pros and cons.
- Derivations / steps: show how to build a dictionary and bag-of-words (list steps and small example). A full-mark answer must show the token->id mapping and final BoW vectors.
- Programs: short Python snippets using one library (for exams, show imports and the minimal code). State any model downloads needed for spaCy.
- Diagrams: draw the pipeline (Raw text → Tokenisation → Normalisation → Analysis → Vectorisation → Modelling) and annotate with library names.
What full-marks answers include:
- Clear definitions (each term bolded or defined separately), assumptions (e.g., model availability), correct small examples (token->id mapping), and if code is shown, explain any external downloads required.
Quick check
- Which library would you choose for fast production NER and why?
- What is the output type of
dictionary.doc2bow(['a','b','a'])in Gensim? - Give one clear difference between stemming and lemmatisation.
Answers: 1. spaCy — it provides fast pre-trained pipeline with tokenisation, POS, dependency parsing and NER. 2. A list of (token_id, count) pairs, e.g. [(id_of_a,2),(id_of_b,1)]. 3. Stemming is crude string-based reduction (may produce non-words); lemmatisation returns a dictionary lemma using morpho-syntactic analysis and requires POS.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?