Detect Sentiment Using Amazon Comprehend Service

The Amazon Comprehend Service - a natural language processing service - can be used to detect the sentiment in a sentence or document. This could be useful for example to determine the sentiment on a product or service from the twitter feed. Note that this may not be conclusive and the service may not be able to understand sarcasm or twisted language.

The detectSentiment function can be used to find the sentiment from a sentence and can be used from Lambda or other services. Below is a sample NodeJS application running in Lambda.


        var AWS = require('aws-sdk');
        var comprehend = new AWS.Comprehend({apiVersion: '2017-11-27'});        
        
        exports.handler = (event, context, callback) => {
            
            var params = {
                LanguageCode: 'en', /* required */
                Text: event.text /* required */
            };
            
            comprehend.detectSentiment(params, function(err, data) {
                if (err) console.log(err, err.stack); // an error occurred
                else     console.log(data);           // successful response
            });
        };            
                
    

Note that the text and language code needs to be supplied for detecting the sentiment. The sentiment output could be POSITIVE, NEUTRAL, MIXED, or NEGATIVE with a confidence score. Below is a sample output from running the above code.


        {   Sentiment: 'NEUTRAL',
            SentimentScore: 
            { 
                Positive: 0.011511518619954586,
                Negative: 0.039009008556604385,
                Neutral: 0.9398699402809143,
                Mixed: 0.00960956048220396 
            } 
        }