top of page

Using Flask to make a sentiment analysis app

Updated: Feb 21, 2022



In the previous blog we learnt to make a simple blogging website using Flask. ( You can find that blog here.) In this blog we will learn to make a web app that will be able to analyze the sentiments of real time tweets.


We will use a sentiment analyzer function offered in nltk package for this purpose. But you may choose to use any other model of your liking.

Lets get started.


You can download all the documents used in this blog by clicking on the download button below:



 

Sentiment Analysis using nltk


We will make a very simple app where a user inputs a text and and the result of its sentiment analysis is displayed.

 

Client Server Communication:


In this case we are expecting to receive an input from the user and then we want to send the result back. To send and receive data from a website we will need to use HTTP methods to communicate between the client and the server.




A client (browser) sends an HTTP request to the server; then the server returns a response to the client. The response contains status information about the request and may also contain the requested content.


We will use 'GET' and 'POST' http methods for this purpose. The GET method is used to request data from a specified resource whereas the POST method is used to send data to a server to create/update a resource.

 


Sentiment Analysis


We will create a python script called app.py in which we will write two functions. The first function will be for performing sentiment analysis on a text. To do this we will use the nltk library.


The code below shows the function definition for sentiment analysis:


import nltk
nltk.download('vader_lexicon')
from nltk.sentiment import SentimentIntensityAnalyzer

def analyse(text):
    sent = SentimentIntensityAnalyzer()
    score = sent.polarity_scores(text)
    
    pos_score = score['pos']
    neg_score = score['neg']
    
    if pos_score > neg_score:
        return 'Positive'
    else:
        return 'Negative'

The above function returns a 'Positive' result if the positive sentiment score for the text is more than the negative sentiment score and vice-versa.


 

Creating a web application using Flask


The second function in our code will be to render the html files to create an interface for our web application and to receive and send data between the client and the server.


Here we will be using two html files. One (home.html) will correspond to the home page which will ask the user to enter the text and the other (result.html) will correspond to the web page that will display the result.


These two files should be stored in a folder named 'templates' in the same directory where the python script app.py is stored as by convention flask looks for HTML files in a folder named 'templates'.


The definition of the second function is shown below:


from flask import Flask, render_template, request

app = Flask(__name__)
 
@app.route('/', methods = ['POST', 'GET'])
def sentiment():
    if request.method == 'POST':
        text = request.home['input']
        result = analyse(text)         
        return render_template("result.html", result = result, text = text)
    else:
        return render_template('home.html')
    

if __name__ == "__main__":
    
    app.run(debug=True)

In the above code:

  • We first create an instance of Flask named app.

  • Then we bind a URL to the function called 'sentiment()' using a decorator function called 'route()'. This decorator converts the function's return value into an HTTP response to be displayed by an HTTP client such as a web browser. '/' URL corresponds to the home/default page. In the decorator function we have passed the values 'POST' and 'GET' for a parameter called methods, which accepts a list of accepted HTTP methods (we have already discussed about these methods in the above section). Doing this here enables us to send and receive data from the web page corresponding to the set URL.

  • In the sentiment function, we first check whether we are encountering a GET or POST request. By default the requests are handled by the GET method, thus on being called our function will first render the home.html file which is basically a form to get input from the user. The html code for this file specifies the http method to be POST. So when the text is submitted by the user the request method changes to POST. When this happens the result.html file is rendered which displays the output.

And with such a few lines of code we have managed to create a sentiment analysis web app. We run the script app.py and it gives us the location of the website to where the app is running. A snippet of the output is shown below:


An example of how the app works is shown below:

Without much hassle we were able to make a sentiment analysis web app. On the same lines you can create many interesting apps using python and flask, so let your creativity flow.


Some other blogs that you may like:


If you need implementation for any of the topics mentioned above or assignment help on any of its variants, feel free contact us.




Comments


bottom of page