Python Sentiment Analysis
Sentiment Analysis in Python
Semantic analysis involves analyzing the general sentiment of an audience. This could be reactions to a news story, a movie, or any tweet about a topic of discussion. Typically, these reactions are captured from social media and merged into a file for analysis using NLP. We first need to define positive and negative words and then develop a method to analyze these words as part of a sentence. We use the sentiment_analyzer module from NLTK. We first perform analysis using individual words and then pairs of words (also known as bigrams). Finally, we use the mark_negation function to mark words with negative sentiment.
import nltk
import nltk.sentiment.sentiment_analyzer
# Analyze single words
def OneWord():
positive_words = ['good', 'progress', 'luck']
text = 'Hard Work brings progress and good luck.'.split()
analysis = nltk.sentiment.util.extract_unigram_feats(text, positive_words)
print(' ** Sentiment with one word **n')
print(analysis)
# Analyze a pair of words
def WithBigrams():
word_sets = [('Regular', 'fit'), ('fit', 'fine')]
text = 'Regular excercise makes you fit and fine'.split()
analysis = nltk.sentiment.util.extract_bigram_feats(text, word_sets)
print('n*** Sentiment with bigrams ***n')
print analysis
# Analyze negative words
def NegativeWord():
text = 'Lack of good health can not bring success to students'.split()
analysis = nltk.sentiment.util.mark_negation(text)
print('n**Sentiment with Negative words**n')
print(analysis)
OneWord()
WithBigrams()
NegativeWord()
When we run the above program, we get the following output −
** Sentiment with one word **
{'contains(luck)': False, 'contains(good)': True, 'contains(progress)': True}
*** Sentiment with bigrams ***
{'contains(fit - fine)': False, 'contains(Regular - fit)': False}
**Sentiment with Negative words**
['Lack', 'of', 'good', 'health', 'can', 'not', 'bring_NEG', 'success_NEG', 'to_NEG', 'students_NEG']