In [1]:
#http://www.geeksforgeeks.org/twitter-sentiment-analysis-using-python/

In [2]:
!pip install tweepy


Requirement already satisfied: tweepy in c:\users\kogentix\anaconda3\lib\site-packages
Requirement already satisfied: requests-oauthlib>=0.4.1 in c:\users\kogentix\anaconda3\lib\site-packages (from tweepy)
Requirement already satisfied: six>=1.7.3 in c:\users\kogentix\anaconda3\lib\site-packages (from tweepy)
Requirement already satisfied: requests>=2.4.3 in c:\users\kogentix\anaconda3\lib\site-packages (from tweepy)
Requirement already satisfied: oauthlib>=0.6.2 in c:\users\kogentix\anaconda3\lib\site-packages (from requests-oauthlib>=0.4.1->tweepy)

In [3]:
!pip install textblob


Requirement already satisfied: textblob in c:\users\kogentix\anaconda3\lib\site-packages
Requirement already satisfied: nltk>=3.1 in c:\users\kogentix\anaconda3\lib\site-packages (from textblob)
Requirement already satisfied: six in c:\users\kogentix\anaconda3\lib\site-packages (from nltk>=3.1->textblob)

In [10]:
import re
import tweepy
from tweepy import OAuthHandler
from textblob import TextBlob
 
class TwitterClient(object):
    '''
    Generic Twitter Class for sentiment analysis.
    '''
    def __init__(self):
        '''
        Class constructor or initialization method.
        '''
        # keys and tokens from the Twitter Dev Console
        consumer_key = 'cUqEqaAhL8iFsowJj50Tf8mwM'
        consumer_secret = 'WQYMRAjZdTC4DcZZrxyi5QFbyerVTzoTirmAy0J4lcBLlSrJMc'
        access_token = '50995744-4dZaS1J21jUhGUBiH5P7EVZI0q5gbQI45caGmjUMk'
        access_token_secret = 'gY1zXKey05klmPFGZzf2R5lcMvSadOWvROcLjQhwxmhyi'
 
        # attempt authentication
        try:
            # create OAuthHandler object
            self.auth = OAuthHandler(consumer_key, consumer_secret)
            # set access token and secret
            self.auth.set_access_token(access_token, access_token_secret)
            # create tweepy API object to fetch tweets
            self.api = tweepy.API(self.auth)
        except:
            print("Error: Authentication Failed")
 
    def clean_tweet(self, tweet):
        '''
        Utility function to clean tweet text by removing links, special characters
        using simple regex statements.
        '''
        return ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)", " ", tweet).split())
 
    def get_tweet_sentiment(self, tweet):
        '''
        Utility function to classify sentiment of passed tweet
        using textblob's sentiment method
        '''
        # create TextBlob object of passed tweet text
        analysis = TextBlob(self.clean_tweet(tweet))
        # set sentiment
        if analysis.sentiment.polarity > 0:
            return 'positive'
        elif analysis.sentiment.polarity == 0:
            return 'neutral'
        else:
            return 'negative'
 
    def get_tweets(self, query, count = 10):
        '''
        Main function to fetch tweets and parse them.
        '''
        # empty list to store parsed tweets
        tweets = []
 
        try:
            # call twitter api to fetch tweets
            fetched_tweets = self.api.search(q = query, count = count)
 
            # parsing tweets one by one
            for tweet in fetched_tweets:
                # empty dictionary to store required params of a tweet
                parsed_tweet = {}
 
                # saving text of tweet
                parsed_tweet['text'] = tweet.text
                # saving sentiment of tweet
                parsed_tweet['sentiment'] = self.get_tweet_sentiment(tweet.text)
 
                # appending parsed tweet to tweets list
                if tweet.retweet_count > 0:
                    # if tweet has retweets, ensure that it is appended only once
                    if parsed_tweet not in tweets:
                        tweets.append(parsed_tweet)
                else:
                    tweets.append(parsed_tweet)
 
            # return parsed tweets
            return tweets
 
        except tweepy.TweepError as e:
            # print error (if any)
            print("Error : " + str(e))
 
def main():
    # creating object of TwitterClient Class
    api = TwitterClient()
    # calling function to get tweets
    tweets = api.get_tweets(query = 'Donald Trump', count = 200)
 
    # picking positive tweets from tweets
    ptweets = [tweet for tweet in tweets if tweet['sentiment'] == 'positive']
    # percentage of positive tweets
    print("Positive tweets percentage: {} %".format(100*len(ptweets)/len(tweets)))
    # picking negative tweets from tweets
    ntweets = [tweet for tweet in tweets if tweet['sentiment'] == 'negative']
    # percentage of negative tweets
    print("Negative tweets percentage: {} %".format(100*len(ntweets)/len(tweets)))
    # percentage of neutral tweets
    print("Neutral tweets percentage: {} %".format(100*(len(tweets) - len(ntweets) - len(ptweets))/len(tweets)))
 
    # printing first 5 positive tweets
    print("\n\nPositive tweets:")
    for tweet in ptweets[:10]:
        print(tweet['text'])
 
    # printing first 5 negative tweets
    print("\n\nNegative tweets:")
    for tweet in ntweets[:10]:
        print(tweet['text'])
 
if __name__ == "__main__":
    # calling main function
    main()


Positive tweets percentage: 42.42424242424242 %
Negative tweets percentage: 16.666666666666668 %
Neutral tweets percentage: 40.90909090909091 %


Positive tweets:
RT @ProudResister: Thank you, Brave Women.
Thank you, Black Voters.
Thank you, Doug Jones.

F+ck you, Donald Trump.
F+ck you, Steve Bannon.…
RT @RVAwonk: I'd like to extend my congratulations to Steve Bannon for masterfully humiliating himself, the Republican Party, AND Donald Tr…
RT @tonyschwartz: It is over for Donald Trump. He has lost in one of the most Republican states in America. God Bless 51 per cent of Alabam…
RT @keithboykin: Doug Jones wins! Donald Trump is on an epic losing streak this year. #AlabamaSenateElection https://t.co/gamrQSCXK4
RT @Fun_Beard: Given his track record, if Donald Trump wants republicans to win, maybe he should start backing democrats?
RT @colbertlateshow: People Magazine released a photo of Natasha Stoynoff, one of Trump’s accusers standing right next to Donald Trump. In…
RT @AngryBlackLady: Ok, who wrote this tweet. Because it sure as shit wasn’t donald j. trump. https://t.co/8NkNtInOnJ
RT @PoliticalShort: Co-founder of Trump dossier firm Fusion GPS confirmed in court filings on Tuesday that he met last year with Justice De…
RT @Amy_Siskind: Wouldn’t it be powerful if tomorrow the 33 US Senators who called on Al Franken to resign called a press conference and ca…
RT @SethAbramson: Congress must immediately launch a bipartisan investigation into the 20+ allegations of sexual assault against Donald Tru…


Negative tweets:
RT @ShaunKing: I’ve counted at least 25 times where Steve Bannon said in speeches that “This election is a referendum on Donald Trump. A vo…
RT @AhmedBaba_: Alabama is further proof that people like Donald Trump and Roy Moore may try and bring out the worst in America but the bes…
RT @funder: I’m so tired of Donald Trump. He’s pure evil.
RT @SenFeinstein: Another disgusting tweet from Thin-Skinned Donald Trump. This man has a problem, plain and simple. He lashes out at women…
@11thHour I know in my heart of hearts, a majority of Americans favor decency. The politicians got it wrong. Once a… https://t.co/P1gMp8znRO
Donald Trump’s staff caught posting ridiculously phony tweet on his account https://t.co/BlwOTN1LPz
RT @ashleyfeinberg: donald trump is hog tied in a bathroom somewhere desperately chewing trying to chew through the door https://t.co/Y70Tm…
Donald Trump & his Crew summed up in one video. This is insane man 🤦🏾‍♂️ This is who YOU guys voted for. https://t.co/1Ht1DqpPbN
Doug Jones declared winner of Alabama Senate race! Donald Trump and child molester the big losers https://t.co/F6bRRuM9ew
poop donald trump Black foot socks by bwet13 https://t.co/SHPlwdpE9s #bwet #bwet13 #etsy

In [ ]: