Slice Text Sentiments with AWS Comprehend

There is a lot of interest in sentiment anaysis. Here is a simple example in Go using AWS Comprehend.

Before you start, be sure to install Go and any included packages first. Once completed, open your favorite text editor and start a new file.

Import Packages

First, you have to declare you file is the main file and import all the relevant packages, including those from the AWS SDK for Go.

package main

import (


Declare Global Variables

Now, let's declare all the variables we are going to use in this program. First, you will create an AWS session with in a specific region. Next, you will create a new comprehend service client using that session. And finally, you will make a list of sentences to analyze.

var (
	sess = session.Must(session.NewSession(&aws.Config{
		Region: aws.String("us-east-1"),

	client = comprehend.New(sess)
	listTexts = []string{
		"The boy read the book.",
		"The girl sang a song.",
		"The man played a guitar",
		"I love riding my bike!",
		"I hate ice cream!",

Wrap Sentiment Analysis

Now, the fun part! We are going to create a wrapper function that takes in text and analyzes it.

func analyzeSentiment(text string) {
	params := comprehend.DetectSentimentInput{}

	req, resp := client.DetectSentimentRequest(&params)

	err := req.Send()
	if err == nil { // resp is now filled
	} else {

Main Function

Finally, we have to create a main function to execute and orchestrate our program. Within the main function, we are going to loop through the listTexts that we created earlier, and pass each text to the sentiment analysis wrapper.

func main() {
	for _, text := range listTexts {

End of file....

Run Program

Save the file as sentiment.go. Then open up the terminal, navigate to the folder where the file is located, and run the program.

$ go run sentiment.go

You should see various output stream down your screen. For each sentence in your list of text, your screen should first print the text, then produce the sentiment analysis. Here is what you should see for the last sentence in the list of texts above.

I hate ice cream!
  Sentiment: "NEGATIVE",
  SentimentScore: {
    Mixed: 0.017810620367527008,
    Negative: 0.5819107890129089,
    Neutral: 0.27721765637397766,
    Positive: 0.12306095659732819

Now, you have the tools to add sentiment analysis to your applications.