Python - 情感分析



語義分析是為了分析受眾的總體意見。它可能是對新聞、電影或關於某個討論問題的推文的反應。通常,此類反應取自社交媒體,並彙總到一個檔案中,以透過 NLP 進行分析。我們將首先定義正面和負面單詞的簡單案例。然後採用一種方法,將這些單詞作為包含這些單詞的句子的一部分進行分析。我們使用 nltk 中的 sentiment_analyzer 模組。我們首先對一個單詞進行分析,然後對成對的單詞(也稱為二元片語)進行分析。最後,我們將標記為負面情緒的單詞放入 mark_negation 函式中。

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

執行上述程式後,將得到以下輸出 -

 ** 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']
廣告
© . All rights reserved.