Sentiment Analysis using Python
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’.
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’)
What’s Coming up next !
In upcoming post, I will visualize the output sentiments in different ways.
Until, Happy Coding !!








