Sunday, 1 April 2018

Basic example of sentiment Analysis - Twitter API

I will demonstrate a basic example of sentiment analysis using in python using jupyter notebook as an editor. We will be analysing tweets from twitter using tweepy.  Tweepy is a python library for accessing twitter API.

We start by creating a new app in https://apps.twitter.com/

Once you create an app in twitter, generate the access token and set the permissions (read/write) accordingly. To accomplish this, you need to key in app name, description and a url. Url could be anything in the right format if you don't have one for yourself.

Once the consumer and access secret keys are generated. Next step would be to fire up python in your choice of editor.

I chose jupyter here. Begin by importing tweepy and textblob libraries. textblob is a python library for text processing.

Assign consumer and access key. Use OAuthHandler method of tweepy by passing consumer key and consumer secret. Then call set_access_token method by passing access token and access secret key.

Once this is done, your authentication is done. Now you can use search method and pass in a text string to search for.

I have searched tweets for 'Indian cuisine' and successfully printed the results back via python.

IMPORTANT : Never expose/share Consumer and Access secret key.







Simplified Text processing Example - Python

Sentiment Analysis can be used to understand human emotions and psychology using their feedback, comments or posts from social media network or any other survey platform.

Below is a very simple example in Python where just in few lines of code we could take a string input and derive a polarity out of it. I used textblob for this.

The output will be a polarity in the range of -1 to +1

-1 being negative sentiment and + 1 is very positive sentiment .

I tested 3 cases as below

a) "Last night food was good, but it was expensive"

The above sentiment resulted in a polarity of 0.06

b) "Last night food was good"

This one resulted in 0.35

c) "I went for running, it felt awesome"

This resulted in 1