Sentiment Analysis with NLP

Nuthakki Mithali Maryah
5 min readJun 4, 2021

Sentiment analyzer simply put takes a text in human language and analyzes the mood behind the text.

Before starting, let us first understand the topic by breaking it down into “sentiment analysis” and “NLP”; after understanding each of them separately, we will look at how great they work hand in hand and build our very own Sentiment Analyzer.

SENTIMENT ANALYSIS: It is as simple as the name suggests, It breaks down the contents of text into individual words and then, finds out if the presented text has a NEGATIVE, POSITIVE or NEUTRAL impact.

Sentiment Analysis can be used in a lot of areas - for example, we can use it to understand the reviews of a movie, book, or even how customers feel about our products; which in return enables us to better the product and deliver it to the customer’s satisfaction.

NATURAL LANGUAGE PROCESSING: It is simply known as NLP and is an essential tool in machine language. It is broadly defined as the automatic manipulation of natural languages, like speech and text, by software. The end goal of NLP is to read, understand and figure out human languages that can henceforth become a valuable asset or a valuable data source.

NLP started when Alan Turing published an article called “Machine and Intelligence”.

NLP is a collection of various libraries, but we will be using only the NLTK(Natural language tool kit library) for the sake of this topic. NLTK provides easy-to-use interphases. It also contains several text processing libraries like tokenization, stemming, parsing, and so on, which we will be using to produce a very efficient text analyzer.

Now, that we know what an NLP and sentiment analysis are; let us start building our very own Sentiment Analyzer.

Software’s Required: Pycharm.

Install the Pycharm software here, we will be using the community version for the project.

Once the software is installed, create a new project

File ->New Project -> ProjectName

Next, open the terminal and install NLTK packages and flask

pip install nltk
pip install flask

Before we begin, we need to keep in mind that there is a basic conventional way to store your flask app components, the different html pages have to be in the templates directory, whereas the javaScript and CSS code should be in the static directory.

Now, let’s create the HTML part to get information and display the result.

Firstly create a new directory named ‘templates’ under the project’s folder, Then create an index.html file inside the templates directory.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<title>Sentiment Analysis</title>
</head>
<body>
<h1 class="heading"> SENTIMENT ANALYSIS</h1>
<form method="POST" class="form">
<textarea class="form-control" type="text" name="inp" placeholder="Enter the text to be Analyzed" id="inp" maxlength="1000" rows="10" cols="40" ></textarea>
<input class="btn-grad" type="submit" name="submit" id="btn" class="btn" >
</form>
<h1 class="result">{{message}}</h1>
</body>
</html>

This is a simple form inherited from bootstrap that contains a textbox to input data, and then a submit button to submit the data and fetch the result with type= “submit”.

Now, let’s move on to working on the data received, i.e. the analysis part. Open up main.py and clear the present content.

Firstly import FLASK and NLTK along with “SentimentIntensityAnalyzer” from “nltk.sentiment.vader”.

main.py

from flask import Flask, render_template, request
from nltk.sentiment.vader import SentimentIntensityAnalyzer
import nltk
nltk.download('vader_lexicon')

Then, assign flask and specify the routing.

main.py

app = Flask(__name__)

@app.route('/', methods=["GET", "POST"])

Finally, let us, define the function to be performed when the button is pressed and return the {{message}} to the HTML file.

main.py

def index():
if request.method == "POST":
inp = request.form.get("inp")
sid = SentimentIntensityAnalyzer()
score = sid.polarity_scores(inp)
neg = score["neg"]
pos = score["pos"]
if neg > pos:
return render_template('index.html', message="The text entered is negative!😢")
elif pos > neg:
return render_template('index.html', message="The text entered is positive!😊")
else:
return render_template('index.html', message="The text entered is neutral!😌")
else:
return render_template('index.html', message="Enter the text to be analyzed")
return render_template('index.html')

Great going! We are almost done; the app should now be functioning perfectly. Now, all that is left is to add in the CSS. But before we get to that, let us verify if our app is working.

In the terminal, enter the following to run the code in the local port,

set FLASK_APP=main.py
set FLASK_ENV=development
flask run

Click on http://127.0.0.1:5000/ and view the analyzer, check if everything is working correctly.

Last but not least, let’s add our CSS-
Begin by creating a new directory called “static” inside creating another directory called styles, then creating a file named “style.CSS”.

How to call an external style? Inside the index.html in the head tag place the below code.

<link  rel="stylesheet" type="text/css" href="{{url_for('static',filename='styles/style.css') }}">

Now let’s, move onto styling;

style.css

body{
margin-top:5%;
margin-left:30%;
margin-right:30%;
background-color:#b6d5a4;
text-align: center;
background-image: url('https://image.freepik.com/free-photo/hand-painted-watercolor-background-with-sky-clouds-shape_24972-1095.jpg');
background-repeat: no-repeat;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
.heading{
padding-bottom:20px;
font-family:Lucida Handwriting;
}
.result{
margin-top:40px;
background-color:#b9d9b3;
padding:40px;
}

.btn-grad {background-image: linear-gradient(to right, #4CB8C4 0%, #3CD3AD 51%, #4CB8C4 100%)}
.btn-grad {
margin: 10px;
padding: 15px 45px;
text-transform: uppercase;
transition: 0.5s;
background-size: 200% auto;
color: white;
box-shadow: 0 0 20px #eee;
border-radius: 10px;
display: block;
font-weight:700;
font-size:25px;
}

.btn-grad:hover {
background-position: right center; /* change the direction of the change here */
color: #fff;
text-decoration: none;
}
The FINAL OUTPUT

That’s it, folks! We have built our very own sentiment analyzer.
We have now learned to use one of the most powerful weapons in today’s time. Feel free to go explore many more topics related to NLP and Machine Learning.

For any further, queries please feel free to contact me:
Mail ID: mithalimaryah@gmail.com
LinkedIn: https://www.linkedin.com/in/nuthakki-mithali-maryah-b254a1194/

~By Nuthakki Mithali Maryah.

--

--