Python - Analyse des sentiments

L'analyse sémantique consiste à analyser l'opinion générale du public. Il peut s'agir d'une réaction à une nouvelle, à un film ou à tout tweet sur un sujet en discussion. Généralement, ces réactions sont extraites des médias sociaux et matraquées dans un fichier à analyser via la PNL. Nous prendrons un cas simple de définition des mots positifs et négatifs en premier. Adoptez ensuite une approche pour analyser ces mots dans le cadre de phrases utilisant ces mots. Nous utilisons le module sentiment_analyzer de nltk. Nous effectuons d'abord l'analyse avec un mot, puis avec des mots appariés également appelés bigrammes. Enfin, nous marquons les mots avec un sentiment négatif tel que défini dans lemark_negation fonction.

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()

Lorsque nous exécutons le programme ci-dessus, nous obtenons la sortie suivante -

** 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']