Twitter Sentiment Analysis using Python Programming.

Sentiment Analysis is the process of estimating the sentiment of people who give feedback to certain event either through written text or through oral communication. Of course the oral communication also has to be converted to written text so that it can be analysed through python program. The sentiment expressed by people may be positive or negative. By assigning weightage to the different words in the sentiment text we calculate a numeric value and that gives us a mathematical evaluation of the sentiment.


  • Customer Fedback − It is vital for business to know the customer’s opinion about product or services. When the customer’s feedback is available as written text we can run the sentiment analysis in Twitter to programmatically find out the overall feedback as positive or negative and take corrective action.

  • Political Campaigns − For political opponents it is very vital to know the reaction of the people to whom they are delivering the speech. If the feedback from the public can be gathered through online platforms like social media platforms, then we can judge the response of the public to a specific speech.

  • Government Initiatives − When the government implements new schemes from time to time they can judge the response to the new scheme by taking public opinion. Often the public put their praise or anger through Twitter.


Below we list the steps that are required to build the sentiment analysis program in python.

  • First we install Tweepy and TextBlob. This module will help us gathering the data from Twitter as well as extracting the text and processing them.

  • Authenticating to Twitter. We need to use the API keys so that the data can be extracted from tweeter.

  • Then we classify the tweets into positive and negative tweets based on the text in the tweet.


import re
import tweepy
from tweepy import OAuthHandler
from textblob import TextBlob
class Twitter_User(object):
   def __init__(self):
      consumer_key = '1ZG44GWXXXXXXXXXjUIdse'
      consumer_secret = 'M59RI68XXXXXXXXXXXXXXXXV0P1L6l7WWetC'
      access_token = '865439532XXXXXXXXXX9wQbgklJ8LTyo3PhVDtF'
      access_token_secret = 'hbnBOz5XXXXXXXXXXXXXefIUIMrFVoc'
         self.auth = OAuthHandler(consumer_key, consumer_secret)
         self.auth.set_access_token(access_token, access_token_secret)
         self.api = tweepy.API(self.auth)
         print("Error: Authentication Failed")
   def pristine_tweet(self, twitter):
      return ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)", " ", twitter).split())
   def Sentiment_Analysis(self, twitter):
      audit = TextBlob(self.pristine_tweet(twitter))
      # set sentiment
      if audit.sentiment.polarity > 0:
         return 'positive'
      elif audit.sentiment.polarity == 0:
         return 'negative'
   def tweet_analysis(self, query, count = 10):
      twitter_tweets = []
         get_twitter = = query, count = count)
         for tweets in get_twitter:
            inspect_tweet = {}
            inspect_tweet['text'] = tweets.text
            inspect_tweet['sentiment'] = self.Sentiment_Analysis(tweets.text)
            if tweets.retweet_count > 0:
               if inspect_tweet not in twitter_tweets:
         return twitter_tweets
      except tweepy.TweepError as e:
         print("Error : " + str(e))
def main():
   api = Twitter_User()
   twitter_tweets = api.tweet_analysis(query = 'Ram Nath Kovind', count = 200)
   Positive_tweets = [tweet for tweet in twitter_tweets if tweet['sentiment'] == 'positive']
   print("Positive tweets percentage: {} %".format(100*len(Positive_tweets)/len(twitter_tweets)))
   Negative_tweets = [tweet for tweet in twitter_tweets if tweet['sentiment'] == 'negative']
   print("Negative tweets percentage: {} %".format(100*len(Negative_tweets)/len(twitter_tweets)))
   for tweet in Positive_tweets[:10]:
   for tweet in Negative_tweets[:10]:
if __name__ == "__main__":


Running the above code gives us the following result −

Positive tweets percentage: 48.78048780487805 %
Negative tweets percentage: 46.34146341463415 %
RT @heartful_ness: "@kanhashantivan presents a model of holistic living. My deep & intimate association with this organisation goes back to…
RT @heartful_ness: Heartfulness Guide @kamleshdaaji welcomes honorable President of India Ram Nath Kovind @rashtrapatibhvn, honorable first…
RT @DrTamilisaiGuv: Very much pleased by the affection shown by our Honourable President Sri Ram Nath Kovind and First Lady madam Savita Ko…
RT @BORN4WIN: Who became the first President of India from dalit community?
A) K.R. Narayanan
B) V. Venkata Giri
C) R. Venkataraman
D) Ram…
RT @Keyadas63: What wuld those #empoweredwomen b termed who reach Hon HC at the drop of a hat
But Demand #Alimony Maint?
RT @heartful_ness: Thousands of @heartful_ness practitioners meditated with Heartfulness Guide @kamleshdaaji at @kanhashantivan & await the…
RT @TurkeyinDelhi: Ambassador Sakir Ozkan Torunlar attended the Joint Session of Parliament of #India and listened the address of H.E. Shri…

Updated on: 14-Feb-2020


Kickstart Your Career

Get certified by completing the course

Get Started