Emotion classification using NRC Lexicon in Python
Last Updated :
03 Sep, 2021
Many a time, for real-world projects, emotion recognition is often just the start of the project. That time writing a whole code on that will not only increase time but also efficiency is hindered.
NRCLexicon is an MIT-approved pypi project by Mark M. Bailey which predicts the sentiments and emotion of a given text. The package contains approximately 27,000 words and is based on the National Research Council Canada (NRC) affect lexicon and the NLTK library’s WordNet synonym sets.
Installation:
To install this module type the below command in the terminal.
pip install NRCLex
Even after the installation of this module, MissingCorpusError may occur while running programs. So it is advised to also install textblob.download_corpora by using the below command on the command prompt.
python -m textblob.download_corpora
Approach:
Python3
from nrclex import NRCLex
|
Python3
text = [ 'hate' , 'lovely' , 'person' , 'worst' ]
|
- Create NRCLex object for each input text.
Python3
for i in range ( len (text)):
emotion = NRCLex(text[i])
|
- Apply methods to classify emotions.
Sr. |
Method |
Description |
1 |
emotion.words |
Return words list. |
2 |
emotion.sentences |
Return sentences list. |
3 |
emotion.affect_list |
Return affect list. |
4 |
emotion.affect_dict |
Return affect dictionary. |
5 |
emotion.raw_emotion_scores |
Return raw emotional counts. |
6 |
emotion.top_emotions |
Return highest emotions. |
7 |
emotion.affect_frequencies |
Return affect frequencies. |
- Emotional affects measured include the following:
- fear
- anger
- anticipation
- trust
- surprise
- positive
- negative
- sadness
- disgust
- joy
Below is the Implementation.
Example 1:
Based on the above approach, the below example classifies various emotions using top_emotions.
Python3
from nrclex import NRCLex
text = [ 'hate' , 'lovely' , 'person' , 'worst' ]
for i in range ( len (text)):
emotion = NRCLex(text[i])
print ( '\n\n' , text[i], ': ' , emotion.top_emotions)
|
Output:
Example 2:
Here a single emotion love is classified using all the methods of NCRLex module.
Python3
from nrclex import NRCLex
text = 'love'
emotion = NRCLex(text)
print ( '\n' , emotion.words)
print ( '\n' , emotion.sentences)
print ( '\n' , emotion.affect_list)
print ( '\n' , emotion.affect_dict)
print ( '\n' , emotion.raw_emotion_scores)
print ( '\n' , emotion.top_emotions)
print ( '\n' , emotion.affect_frequencies)
|
Output:
Share your thoughts in the comments
Please Login to comment...