Skip to content

Instantly share code, notes, and snippets.

@javaguirre
Created April 4, 2017 08:48
Show Gist options
  • Save javaguirre/9aee565366e3111409f26ec667e80789 to your computer and use it in GitHub Desktop.
Save javaguirre/9aee565366e3111409f26ec667e80789 to your computer and use it in GitHub Desktop.
Sentiment analysis with Python NLTK and IBM Tone Analyzer
import json
from watson_developer_cloud import ToneAnalyzerV3
from nltk.sentiment.vader import SentimentIntensityAnalyzer
class SentimentService():
def __init__(self):
self.service = SentimentIntensityAnalyzer()
def analyze(self, text):
return self.format_polarity(self.service.polarity_scores(text))
def format_polarity(self, polarity):
return polarity
class ToneWatsonService():
DEFAULT_VERSION = '2016-02-11'
def __init__(self, access):
'''
access is a dict with username and password keys
'''
self.access = access
def process(self, text):
'''
Response:
{
"document_tone": {
"tone_categories": [
{
"tones": [
{
"score": 0.000264,
"tone_id": "anger",
"tone_name": "Anger"
},
{
"score": 0.00016,
"tone_id": "disgust",
"tone_name": "Disgust"
},
{
"score": 0.000376,
"tone_id": "fear",
"tone_name": "Fear"
},
{
"score": 0.996063,
"tone_id": "joy",
"tone_name": "Joy"
},
{
"score": 0.001101,
"tone_id": "sadness",
"tone_name": "Sadness"
}
],
"category_id": "emotion_tone",
"category_name": "Emotion Tone"
},
{
"tones": [
{
"score": 0.0,
"tone_id": "analytical",
"tone_name": "Analytical"
},
{
"score": 0.97759,
"tone_id": "confident",
"tone_name": "Confident"
},
{
"score": 0.0,
"tone_id": "tentative",
"tone_name": "Tentative"
}
],
"category_id": "writing_tone",
"category_name": "Writing Tone"
},
{
"tones": [
{
"score": 0.096859,
"tone_id": "openness_big5",
"tone_name": "Openness"
},
{
"score": 0.264058,
"tone_id": "conscientiousness_big5",
"tone_name": "Conscientiousness"
},
{
"score": 0.472657,
"tone_id": "extraversion_big5",
"tone_name": "Extraversion"
},
{
"score": 0.61522,
"tone_id": "agreeableness_big5",
"tone_name": "Agreeableness"
},
{
"score": 0.104851,
"tone_id": "neuroticism_big5",
"tone_name": "Emotional Range"
}
],
"category_id": "social_tone",
"category_name": "Social Tone"
}
]
}
}
'''
tone_analyzer = ToneAnalyzerV3(
username=self.access['username'],
password=self.access['password'],
version=self.DEFAULT_VERSION)
return tone_analyzer.tone(text)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment