Sitemap
Annamalai Selvam

Annamalai Selvam

Hands on experience in Angular, React, Spring boot, Node Js, Firebase

Sentiment Analysis using Python

2 min readJun 9, 2019

--

Press enter or click to view image in full size

Introduction

Sentiment analysis has been predominantly used in data science for analysis of customer feedback on products and reviews. It has also become popular to analyses user tweets — positive, negative or neutral by crawling twitter through APIs.

“Will you believe ,if I say that the sentiment analysis can be done in just 18 lines of code ? “ Oh,No! Don’t laugh! Until you scroll off this article fully!!

Before stepping into the coding process, we need to do couple of installation process.

Get Annamalai Selvam’s stories in your inbox

Join Medium for free to get updates from this writer.

Tweepy: Python client for the official Twitter API.

pip install tweepy

TextBlob: Python library for processing textual data.

pip install textblob

Authentication:
In order to fetch tweets through Twitter API, we need to register an App through their twitter account. Follow these steps for the same:

  • Open this link and click the button: ‘Create New App’
  • Fill the application details. You can leave the callback url field empty.
  • Once the app is created, you will be redirected to the app page.
  • Open the ‘Keys and Access Tokens’ tab.
  • Copy ‘Consumer Key’, ‘Consumer Secret’, ‘Access token’ and ‘Access Token Secret’.
Press enter or click to view image in full size

Implementation:

import tweepy
from textblob import TextBlob
# keys and tokens from the Twitter Dev Console
consumer_key = ‘XXXXXXXXXXXXXXXXXXXXXXXX’
consumer_secret = ‘XXXXXXXXXXXXXXXXXXXXXXXXXXXX’
access_token = ‘XXXXXXXXXXXXXXXXXXXXXXXXXXXX’
access_token_secret = ‘XXXXXXXXXXXXXXXXXXXXXXXXX’
# attempt authentication
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
# create tweepy API object to fetch tweets
api = tweepy.API(auth)
tweets=api.search(‘Annamalai’)
for t in tweets:
analysis = TextBlob(t.text)
if analysis.sentiment.polarity > 0:
print(‘Happy and Excited !!’)
elif analysis.sentiment.polarity == 0:
print(‘Unbiased’)
else:
print(‘Sad’)

Press enter or click to view image in full size

What’s Coming up next !

In upcoming post, I will visualize the output sentiments in different ways.

Until, Happy Coding !!

--

--

Annamalai Selvam

Written by Annamalai Selvam

Hands on experience in Angular, React, Spring boot, Node Js, Firebase