Getting Started with TextBlob in Python

getting-started-textblob-python
Image by Author
 

TextBlob is a Python library for processing textual data. Built on top of NLTK (Natural Language Toolkit), it provides a clean API for common NLP tasks: sentiment analysis, part-of-speech tagging, noun phrase extraction, and tokenization.

If you work with text data in Python, whether that’s customer reviews, survey responses, or social media posts, TextBlob is a solid starting point that doesn’t require deep knowledge of computational linguistics. This tutorial covers installation, environment setup, and three practical examples: sentiment scoring, part-of-speech tagging, and batch text processing with pandas.

Environment Setup

Installing the Required Packages

Before writing any code, install everything this tutorial needs:

 
pip install textblob nltk pandas numpy matplotlib seaborn ipykernel

Each package plays a specific role:

Package Role in This Tutorial
textblob Core library for sentiment, tokenization, and word analysis
nltk The engine TextBlob runs on; provides datasets and models
pandas Organizing and batch-processing text data in tables
numpy Numerical operations on scores and frequencies
matplotlib / seaborn Visualizing polarity distributions and word frequency charts
ipykernel Registers this environment as a selectable Jupyter kernel

Why the Corpus Download Can’t Be Skipped

Think of TextBlob as an interface layered on top of NLTK. It simplifies the syntax, but NLTK does the actual work, which means TextBlob depends on NLTK datasets and pre-trained models that don’t come bundled with the pip install. You have to download them separately.

Run this one-time command before anything else:

 
python -m textblob.download_corpora

This pulls down the resources TextBlob relies on:

Resource What It Does
punkt Tokenization rules for splitting text into words and sentences
averaged_perceptron_tagger Pre-trained model for identifying parts of speech
movie_reviews Labeled dataset powering the Naive Bayes sentiment classifier
wordnet Lexical database used for word meanings and subjectivity scoring
brown / conll2000 Supporting corpora for POS tagging and phrase chunking

Skipping this step won’t cause an error on import.It fails silently. You’ll only hit a LookupError once you call something like .sentiment or .words. Running the download upfront avoids that entirely.

This is a one-time setup per machine. Once downloaded, these resources are stored locally and available to any notebook or script in the environment.

Sentiment Analysis and Tokenization

With setup out of the way, let’s look at the two tasks TextBlob is most often used for: sentiment scoring and tokenization.

TextBlob returns sentiment as two values. Polarity ranges from -1.0 (most negative) to 1.0 (most positive). Subjectivity ranges from 0.0 (fully objective) to 1.0 (highly subjective).

The code below creates a TextBlob object from a short review and extracts both sentiment scores alongside basic tokenization:

 
from textblob import TextBlob

review = "The product was surprisingly good. Fast shipping, great packaging."
blob = TextBlob(review)

print("Polarity:    ", blob.sentiment.polarity)
print("Subjectivity:", blob.sentiment.subjectivity)
print("Sentences:   ", blob.sentences)
print("Words:       ", blob.words[:8])

Output:

 
Polarity:     0.56
Subjectivity: 0.65
Sentences:    [Sentence("The product was surprisingly good."), Sentence("Fast shipping, great packaging.")]
Words:        WordList(['The', 'product', 'was', 'surprisingly', 'good', 'Fast', 'shipping', 'great'])

A polarity of 0.56 indicates a moderately positive tone. Subjectivity at 0.65 means the text leans opinion-based rather than factual. The .sentences attribute splits text at sentence boundaries automatically, and .words returns a clean tokenized list ready for further analysis.

Part-of-Speech Tagging

Part-of-speech (POS) tagging labels each word with its grammatical role: noun, verb, adjective, and so on. This comes in handy when you want to pull only descriptive language from reviews, or identify the subjects being discussed.

TextBlob uses the averaged_perceptron_tagger from NLTK to produce Penn Treebank-style tags. The code below tags a sentence and filters the results for adjectives and nouns:

 
from textblob import TextBlob

sentence = "The quick brown fox jumped over the lazy dog near the riverbank."
blob = TextBlob(sentence)

print("All tags:", blob.tags)

adjectives = [word for word, tag in blob.tags if tag in ("JJ", "JJR", "JJS")]
nouns      = [word for word, tag in blob.tags if tag in ("NN", "NNS", "NNP")]

print("Adjectives:", adjectives)
print("Nouns:     ", nouns)

Output:

 
All tags: [('The', 'DT'), ('quick', 'JJ'), ('brown', 'NN'), ('fox', 'NN'), ('jumped', 'VBD'), ('over', 'IN'), ('the', 'DT'), ('lazy', 'JJ'), ('dog', 'NN'), ('near', 'IN'), ('the', 'DT'), ('riverbank', 'NN')]
Adjectives: ['quick', 'lazy']
Nouns:      ['brown', 'fox', 'dog', 'riverbank']

JJ marks standard adjectives, while JJR and JJS catch comparative and superlative forms. NN covers singular nouns, with NNS and NNP handling plurals and proper nouns. Filtering by tag gives you targeted vocabulary extraction with no manual string parsing required.

Batch Processing with Pandas

In practice, text analysis rarely happens one sentence at a time. More often, you’re working with a DataFrame full of text entries, customer reviews, support tickets, survey responses, and you need to score all of them at once.

The code below creates a small reviews DataFrame, scores each row with TextBlob using .apply(), and displays the results:

 
import pandas as pd
from textblob import TextBlob

reviews = [
    "Absolutely loved this product. Would buy again.",
    "Terrible quality. Broke after one use.",
    "Decent value for the price, nothing special.",
    "Outstanding customer service and fast delivery.",
    "Not what I expected. Pretty disappointed overall."
]

df = pd.DataFrame({"review": reviews})
df["polarity"]     = df["review"].apply(lambda x: TextBlob(x).sentiment.polarity)
df["subjectivity"] = df["review"].apply(lambda x: TextBlob(x).sentiment.subjectivity)
print(df.to_string(index=False))

Output:

 
                                           review  polarity  subjectivity
  Absolutely loved this product. Would buy again.  0.700000      0.800000
           Terrible quality. Broke after one use. -1.000000      1.000000
     Decent value for the price, nothing special.  0.261905      0.619048
  Outstanding customer service and fast delivery.  0.350000      0.737500
Not what I expected. Pretty disappointed overall. -0.150000      0.537500

Using .apply() with a lambda keeps things concise and avoids manual looping. The resulting columns give you a structured view of sentiment across your dataset, one you can sort, filter, or hand off to matplotlib or seaborn to visualize polarity distributions.

Conclusion

TextBlob is a clean, approachable way to get started with text analysis in Python. In this tutorial, you set up the environment, downloaded the required NLTK corpora, and worked through three practical examples covering sentiment scoring, part-of-speech tagging, and batch processing with pandas.

For next steps, check out TextBlob’s built-in spelling correction and language detection features. If you need a sentiment tool built specifically for short-form social media text, VADER is worth a look. And if you want more control over the underlying pipeline, comparing TextBlob’s outputs directly with raw NLTK is a good way to understand exactly what the abstraction layer is doing for you.

Leave a Reply

Your email address will not be published. Required fields are marked *