Python - Analisi del sentiment

L'analisi semantica riguarda l'analisi dell'opinione generale del pubblico. Può essere una reazione a una notizia, un film o un tweet su un argomento in discussione. Generalmente, tali reazioni vengono prese dai social media e raggruppate in un file da analizzare attraverso la PNL. Considereremo prima un semplice caso di definizione di parole positive e negative. Quindi adottare un approccio per analizzare quelle parole come parte di frasi che utilizzano quelle parole. Usiamo il modulo sentiment_analyzer di nltk. Effettuiamo prima l'analisi con una parola e poi con parole accoppiate chiamate anche bigram. Infine, contrassegniamo le parole con un sentimento negativo come definito inmark_negation funzione.

import nltk
import nltk.sentiment.sentiment_analyzer 
# Analysing for 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) 
# Analysing for 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
# Analysing the negation 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()

Quando eseguiamo il programma sopra, otteniamo il seguente 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']