Python Text Processing 简明教程

Python - Sentiment Analysis

语义分析是对受众的总体意见进行分析。它可能是对新闻、电影或有关正在讨论的某一问题的推文的反应。通常,此类反应是从社交媒体中获取的,并分组到一个文件中,以便通过 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']