Sentiment Analysis in Go
Sentiment Analysis is the process of identifying and classifying assessments which are present in form of text, that represents the inclination of writer’s sensibility towards a particular entity.
Sentiment analysis is particularly useful for monitoring of reviews, tweets or feedback.
Here, we are analyzing sentiments out of IMDB Movie reviews.
This dataset is available at: https://www.kaggle.com/lakshmi25npathi/imdb-dataset-of-50k-movie-reviews
Dataset contains 50k movie reviews along with the sentiment mentioned, but we are going to just use the movie review and not the provided sentiment in the file.
We are going to use the go package : https://github.com/cdipaolo/sentiment
This is just a started code where we are going to read reviews from a CSV file and print the sentiment of the movie review.
First, we have to install the package by running
go get -u github.com/cdipaolo/sentiment
Create a main.go
file in your project directory and you can use the following snippets.
Importing the packages
package main
import (
"encoding/csv"
"fmt"
"io"
"log"
"os" "github.com/cdipaolo/sentiment"
)
Reading the CSV file that contains the movie reviews
func main() {
// Open the file
csvfile, err := os.Open("data/IMDBDataset.csv")
if err != nil {
log.Fatalln("Couldn't open the csv file", err)
}
defer csvfile.Close()
// Parse the file
r := csv.NewReader(csvfile)
Create a sentiment Analysis Model
- This sentiment analysis model uses Naive Bayes classification model for prediction.
// Creating Sentiment Analysis Model
model, err := sentiment.Restore()
if err != nil {
panic(err)
}
var analysis *sentiment.Analysis
Iterating through records, we read each record and determine its sentiment.
// Iterate through the records
for {
// Read each record from csv
record, err := r.Read()
if err == io.EOF {
break
}
if err != nil {
log.Fatal(err)
}
analysis = model.SentimentAnalysis(record[0], sentiment.English)
var sentiment string
if analysis.Score == 1 {
sentiment = "positive"
} else {
sentiment = "negative"
}
fmt.Printf("Review: %s \n and Sentiment:%s\n", record[0], sentiment)
}
Model by default returns 0 or 1 for the sentiment(negative=0, positive=1). Here, we just put up a conditional statement to print out the actual sentiment of the review.
Full Code