📜  Python情绪分析

📅  最后修改于: 2020-11-06 06:22:01             🧑  作者: Mango


语义分析是关于分析受众的普遍看法。这可能是对新闻,电影或有关正在讨论的某些问题的任何推文的反应。通常,此类反应来自社交媒体,并汇总到一个文件中,以通过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']