Perform Sentiment Analysis on Sentences

· 306 words · 2 minutes read

Sentiment analysis is an interesting technique of judging whether a sentence, word or paragraph is considered a positive or negative thing. It’s often used against datasets like tweets as it allows you to summarize a mass of small sentences into an easy to understand stat.

In our example, we’re using a package called sentiment - which was trained against IMDB comment data - to judge whether our example sentences are positive or negative. Because it was trained on short comments about films it might not be appropriate for your use case.

Example Code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package main

import (
	"log"
	"github.com/cdipaolo/sentiment"
)

func main() {

	model, err := sentiment.Restore()
	if err != nil {
		panic(err)
	}

	var analysis *sentiment.Analysis
	var text string

	// Negative Example
	text = "Your mother is an awful lady"
	analysis = model.SentimentAnalysis(text, sentiment.English)
	if analysis.Score == 1 {
		log.Printf("%s - Score of %d = Positive Sentiment\n", text, analysis.Score)
	} else {
		log.Printf("%s - Score of %d = Negative Sentiment\n", text, analysis.Score)
	}

	// Positive Example
	text = "Your mother is a lovely lady"
	analysis = model.SentimentAnalysis(text, sentiment.English)
	if analysis.Score == 1 {
		log.Printf("%s - Score of %d = Positive Sentiment\n", text, analysis.Score)
	} else {
		log.Printf("%s - Score of %d = Negative Sentiment\n", text, analysis.Score)
	}
}

The response of the SentimentAnalysis method returns more data then is shown in the example (struct shown below). We’re just using the ‘Score’ of the whole string, but it has analysed each word within the sentence - which can be accessed in the ‘Words’ slice.

type Analysis struct {
    Language  Language        `json:"lang"`
    Words     []Score         `json:"words"`
    Sentences []SentenceScore `json:"sentences,omitempty"`
    Score     uint8           `json:"score"`
}

Image of Author Edd Turtle

Author:  Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code. He loves coding, but also enjoys cycling and camping in his spare time.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below - Thanks for reading!