Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Emotion classification using NRC Lexicon in Python
Emotion identification or recognition is the ability of a person or system to detect specific emotions from text and categorize them into distinct emotional categories. Unlike traditional sentiment analysis that only classifies text as positive or negative, emotion classification provides deeper insights into human emotions.
Emotion Classification in Python using the NRC Lexicon offers a more nuanced approach than basic sentiment analysis. It can identify multiple emotions simultaneously and provides probability scores for each detected emotion.
The NRC Emotion Lexicon, developed by the National Research Council of Canada, contains over 27,000 terms mapped to emotions. It's based on WordNet synonym sets and provides comprehensive emotion analysis capabilities.
Emotion Categories
The NRC Lexicon classifies words into the following emotional categories ?
fear anxiety, worry, terror
anger rage, fury, irritation
anticipation expectation, hope
trust confidence, faith
surprise amazement, shock
positive general positive sentiment
negative general negative sentiment
sadness sorrow, grief
disgust revulsion, distaste
joy happiness, delight
Installation
Install the required packages using pip ?
pip install NRCLex pip install textblob python -m textblob.download_corpora
Basic Usage
Here's how to classify emotions for individual words ?
from nrclex import NRCLex
# Analyze a single word
word = "happy"
emotion = NRCLex(word)
print(f"Word: {word}")
print(f"Top emotions: {emotion.top_emotions}")
print(f"Raw scores: {emotion.raw_emotion_scores}")
Word: happy
Top emotions: [('joy', 1.0), ('positive', 1.0)]
Raw scores: {'fear': 0, 'anger': 0, 'anticipation': 0, 'trust': 0, 'surprise': 0, 'positive': 1, 'negative': 0, 'sadness': 0, 'disgust': 0, 'joy': 1}
Analyzing Multiple Words
Process a list of words to compare their emotional profiles ?
from nrclex import NRCLex
words = ['happy', 'sad', 'angry', 'excited', 'worried']
print("Emotion Analysis Results:")
print("-" * 40)
for word in words:
emotion = NRCLex(word)
top_emotions = emotion.top_emotions[:2] # Get top 2 emotions
print(f"{word:10} : {top_emotions}")
Emotion Analysis Results:
----------------------------------------
happy : [('joy', 1.0), ('positive', 1.0)]
sad : [('negative', 1.0), ('sadness', 1.0)]
angry : [('anger', 1.0), ('negative', 1.0)]
excited : [('joy', 0.5), ('positive', 0.5)]
worried : [('fear', 0.5), ('negative', 0.5)]
Text Sentence Analysis
Analyze emotions in complete sentences ?
from nrclex import NRCLex
sentences = [
"I am feeling wonderful today",
"This situation makes me nervous and scared",
"What an amazing surprise this is"
]
for i, sentence in enumerate(sentences, 1):
emotion = NRCLex(sentence)
print(f"Sentence {i}: {sentence}")
print(f"Top emotions: {emotion.top_emotions[:3]}")
print(f"Affect frequency: {emotion.affect_frequencies}")
print("-" * 50)
Sentence 1: I am feeling wonderful today
Top emotions: [('positive', 0.5), ('joy', 0.25), ('trust', 0.25)]
Affect frequency: {'positive': 2, 'joy': 1, 'trust': 1}
--------------------------------------------------
Sentence 2: This situation makes me nervous and scared
Top emotions: [('fear', 0.5), ('negative', 0.5)]
Affect frequency: {'fear': 2, 'negative': 2}
--------------------------------------------------
Sentence 3: What an amazing surprise this is
Top emotions: [('positive', 0.4), ('surprise', 0.2), ('joy', 0.2)]
Affect frequency: {'positive': 2, 'surprise': 1, 'joy': 1}
Key Methods
| Method | Description | Returns |
|---|---|---|
top_emotions |
Most prominent emotions | List of (emotion, score) tuples |
raw_emotion_scores |
Raw emotion counts | Dictionary with emotion counts |
affect_frequencies |
Emotion frequencies | Dictionary of emotion frequencies |
words |
Processed word list | List of words |
Practical Example
Build a simple emotion classifier for product reviews ?
from nrclex import NRCLex
def analyze_review_emotions(review_text):
"""Analyze emotions in a product review"""
emotion = NRCLex(review_text)
# Get dominant emotion
top_emotion = emotion.top_emotions[0] if emotion.top_emotions else ("neutral", 0)
# Check if positive or negative overall
positive_score = emotion.raw_emotion_scores.get('positive', 0)
negative_score = emotion.raw_emotion_scores.get('negative', 0)
sentiment = "Positive" if positive_score > negative_score else "Negative" if negative_score > positive_score else "Neutral"
return {
'dominant_emotion': top_emotion[0],
'emotion_score': top_emotion[1],
'overall_sentiment': sentiment,
'top_emotions': emotion.top_emotions[:3]
}
# Test with sample reviews
reviews = [
"This product is absolutely amazing and I love it!",
"Terrible quality, very disappointed with this purchase",
"It's okay, nothing special but works fine"
]
for i, review in enumerate(reviews, 1):
result = analyze_review_emotions(review)
print(f"Review {i}: {review}")
print(f"Analysis: {result}")
print("-" * 60)
Review 1: This product is absolutely amazing and I love it!
Analysis: {'dominant_emotion': 'positive', 'emotion_score': 0.4, 'overall_sentiment': 'Positive', 'top_emotions': [('positive', 0.4), ('joy', 0.2), ('surprise', 0.2)]}
------------------------------------------------------------
Review 2: Terrible quality, very disappointed with this purchase
Analysis: {'dominant_emotion': 'negative', 'emotion_score': 0.6666666666666666, 'overall_sentiment': 'Negative', 'top_emotions': [('negative', 0.6666666666666666), ('sadness', 0.3333333333333333)]}
------------------------------------------------------------
Review 3: It's okay, nothing special but works fine
Analysis: {'dominant_emotion': 'positive', 'emotion_score': 1.0, 'overall_sentiment': 'Positive', 'top_emotions': [('positive', 1.0)]}
Conclusion
The NRC Lexicon provides powerful emotion classification capabilities beyond basic sentiment analysis. It supports over 100 languages and finds applications in healthcare, psychology, social media analysis, and human-computer interaction. Use NRCLex for comprehensive emotion detection in text analysis projects.
