Python 情感分析
语义分析是关于分析观众的总体意见。它可以是对某个新闻、电影或是关于某个讨论话题的推文的反应。通常,这些反应来自社交媒体,并被合并到一个文件中,通过自然语言处理进行分析。我们首先简单地定义积极和消极的词汇。然后采取一种方法来分析那些包含这些词汇的句子。我们使用nltk中的sentiment_analyzer模块。我们首先使用一个词进行分析,然后使用成对的词也称为bigrams进行分析。最后,我们使用 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']