Skip to main content

How to perform stemming using python?

Introduction:

In the realm of natural language processing and text analysis, the preprocessing of textual data plays a pivotal role in extracting meaningful insights. Stemming, a fundamental technique in this domain, involves reducing words to their base or root form, thereby simplifying the analysis of language and enhancing the efficiency of various language-based applications.

Python, as a versatile programming language, provides several libraries and tools for stemming, each offering unique features and approaches. In this discussion, we explore popular Python libraries such as NLTK, TextBlob, spaCy, and others, showcasing their capabilities in stemming and related text processing tasks. From traditional stemming algorithms like Porter stemming to advanced lemmatization techniques, these tools cater to a range of linguistic requirements and project contexts.

Let's delve into the nuances of stemming in Python, highlighting the strengths and applications of each library, and aiding in the selection of the most suitable approach based on specific project needs and language considerations.

NLTK:

In Python, you can perform stemming using various libraries, and one of the most commonly used ones is the Natural Language Toolkit (NLTK). NLTK provides a Porter stemmer that you can use for stemming. Here's a simple example:

from nltk.stem import PorterStemmer
from nltk.tokenize import word_tokenize

# Create a Porter stemmer instance
porter = PorterStemmer()

# Example text
text = "Stemming is a technique used to reduce words to their root form."

# Tokenize the text
words = word_tokenize(text)

# Apply stemming to each word
stemmed_words = [porter.stem(word) for word in words]

# Print the original words and their stemmed forms
for original, stemmed in zip(words, stemmed_words):
    print(f"{original} -> {stemmed}")

Before running this code, make sure you have the NLTK library installed. You can install it using pip install nltk.

 Note that stemming may not always produce perfect results, as it tends to be more aggressive than lemmatization. If you need more accurate word transformations, you might consider using lemmatization. The NLTK library also provides a WordNet lemmatizer.

from nltk.stem import WordNetLemmatizer
from nltk.tokenize import word_tokenize

# Create a WordNet lemmatizer instance
lemmatizer = WordNetLemmatizer()

# Example text
text = "Lemmatization is a technique used to reduce words to their base form."

# Tokenize the text
words = word_tokenize(text)

# Apply lemmatization to each word
lemmatized_words = [lemmatizer.lemmatize(word) for word in words]

# Print the original words and their lemmatized forms
for original, lemmatized in zip(words, lemmatized_words):
    print(f"{original} -> {lemmatized}")

 

Textblob:

TextBlob is another popular natural language processing library in Python that simplifies text processing tasks, including stemming. Here's an example of stemming using TextBlob:

from textblob import TextBlob

# Example text
text = "Stemming is a technique used to reduce words to their root form."

# Create a TextBlob object
blob = TextBlob(text)

# Apply stemming to each word in the text
stemmed_words = [word.stem() for word in blob.words]

# Print the original words and their stemmed forms
for original, stemmed in zip(blob.words, stemmed_words):
    print(f"{original} -> {stemmed}")
 

TextBlob is built on top of NLTK, so it also uses the Porter stemmer. Keep in mind that stemming may not be suitable for all applications, and in some cases, lemmatization might be preferred for more accurate results.

 

Spacy

you can perform stemming-like operations using spaCy, although spaCy itself does not provide a traditional stemming algorithm. Instead, it uses lemmatization, which is a more advanced technique that reduces words to their base or root form.

Here's an example of using spaCy for lemmatization:

import spacy

# Load the English language model
nlp = spacy.load("en_core_web_sm")

# Example text
text = "Lemmatization is a technique used to reduce words to their base form."

# Process the text with spaCy
doc = nlp(text)

# Extract lemmatized forms of each token
lemmatized_words = [token.lemma_ for token in doc]

# Print the original words and their lemmatized forms
for original, lemmatized in zip(doc, lemmatized_words):
    print(f"{original.text} -> {lemmatized}")
 

You can install the English language model using:

python -m spacy download en_core_web_sm

While spaCy doesn't have a traditional stemming algorithm, its lemmatization approach often provides more meaningful results in the context of natural language processing tasks. If you specifically need stemming, you might want to use NLTK or TextBlob, as shown in the previous examples.

Other packages:

Apart from NLTK, TextBlob, and spaCy, there are several other libraries in Python that provide stemming capabilities. Here are a few examples:

Stemming in scikit-learn: 

Scikit-learn, a popular machine learning library, has a module for text feature extraction that includes a simple stemmer. It uses the Porter stemming algorithm.

from sklearn.feature_extraction.text import ENGLISH_STOP_WORDS
from sklearn.feature_extraction.text import CountVectorizer

# Example text
text = ["Stemming is a technique used to reduce words to their root form."]

# Create a CountVectorizer with a simple stemmer
vectorizer = CountVectorizer(stop_words=ENGLISH_STOP_WORDS, analyzer='word', lowercase=True, tokenizer=nltk.word_tokenize)

# Fit and transform the text
X = vectorizer.fit_transform(text)

# Get the feature names (words after stemming)
feature_names = vectorizer.get_feature_names_out()

print(feature_names)

 

Note: In this example, we use the NLTK tokenizer for simplicity.

Snowball Stemmer: 

The Snowball Stemmer is a stemming algorithm that supports multiple languages. The nltk library also includes the Snowball Stemmer for several languages.

from nltk.stem import SnowballStemmer

# Example text
text = "Stemming is a technique used to reduce words to their root form."

# Create a Snowball stemmer for English
snowball_stemmer = SnowballStemmer("english")

# Apply stemming to each word
stemmed_words = [snowball_stemmer.stem(word) for word in word_tokenize(text)]

print(stemmed_words)

 

Porter Stemmer from PorterStemmer package: 

There is a separate Python package called PorterStemmer that provides the Porter stemming algorithm.

from PorterStemmer import PorterStemmer

# Example text
text = "Stemming is a technique used to reduce words to their root form."

# Create a Porter stemmer instance
porter = PorterStemmer()

# Apply stemming to each word
stemmed_words = [porter.stem(word) for word in word_tokenize(text)]

print(stemmed_words)

 

Choose the library or package that best fits your needs based on your specific requirements and the overall context of your project. Each library may have different algorithms, features, and performance characteristics.

Conclusion

In conclusion, stemming is a crucial text preprocessing technique that involves reducing words to their base or root form, enhancing text analysis and information retrieval. In Python, various libraries provide tools for stemming, each with its strengths and focus.

NLTK and TextBlob are versatile natural language processing libraries offering stemming and other text processing functionalities. Meanwhile, spaCy primarily focuses on lemmatization, a more context-aware approach to word normalization. Additionally, scikit-learn, with its CountVectorizer, supports basic stemming for feature extraction in machine learning tasks.

Moreover, language-specific stemmers like the Snowball Stemmer, available in NLTK, cater to a range of languages, while specialized packages like PorterStemmer provide specific algorithms like the classic Porter stemming.

When choosing a stemming tool, it's essential to consider the nature of your text data, language requirements, and the specific goals of your project. While stemming aids in simplifying text, enhancing model performance, and reducing dimensionality, the choice between stemming and lemmatization may depend on the desired level of linguistic precision. In practice, experimenting with different libraries and methods can help identify the most suitable approach for a given application.

Comments

Popular posts from this blog

Tinder bio generation with OpenAI GPT-3 API

Introduction: Recently I got access to OpenAI API beta. After a few simple experiments, I set on creating a simple test project. In this project, I will try to create good tinder bio for a specific person.  The abc of openai API playground: In the OpenAI API playground, you get a prompt, and then you can write instructions or specific text to trigger a response from the gpt-3 models. There are also a number of preset templates which loads a specific kind of prompt and let's you generate pre-prepared results. What are the models available? There are 4 models which are stable. These are: (1) curie (2) babbage (3) ada (4) da-vinci da-vinci is the strongest of them all and can perform all downstream tasks which other models can do. There are 2 other new models which openai introduced this year (2021) named da-vinci-instruct-beta and curie-instruct-beta. These instruction models are specifically built for taking in instructions. As OpenAI blog explains and also you will see in our

Can we write codes automatically with GPT-3?

 Introduction: OpenAI created and released the first versions of GPT-3 back in 2021 beginning. We wrote a few text generation articles that time and tested how to create tinder bio using GPT-3 . If you are interested to know more on what is GPT-3 or what is openai, how the server look, then read the tinder bio article. In this article, we will explore Code generation with OpenAI models.  It has been noted already in multiple blogs and exploration work, that GPT-3 can even solve leetcode problems. We will try to explore how good the OpenAI model can "code" and whether prompt tuning will improve or change those performances. Basic coding: We will try to see a few data structure coding performance by GPT-3. (a) Merge sort with python:  First with 200 words limit, it couldn't complete the Write sample code for merge sort in python.   def merge(arr, l, m, r):     n1 = m - l + 1     n2 = r- m       # create temp arrays     L = [0] * (n1)     R = [0] * (n

What is Bort?

 Introduction: Bort, is the new and more optimized version of BERT; which came out this october from amazon science. I came to know about it today while parsing amazon science's news on facebook about bort. So Bort is the newest addition to the long list of great LM models with extra-ordinary achievements.  Why is Bort important? Bort, is a model of 5.5% effective and 16% total size of the original BERT model; and is 20x faster than BERT, while being able to surpass the BERT model in 20 out of 23 tasks; to quote the abstract of the paper,  ' it obtains performance improvements of between 0 . 3% and 31%, absolute, with respect to BERT-large, on multiple public natural language understanding (NLU) benchmarks. ' So what made this achievement possible? The main idea behind creation of Bort is to go beyond the shallow depth of weight pruning, connection deletion or merely factoring the NN into different matrix factorizations and thus distilling it. While methods like knowle