Import required libraries

In [0]:
# Already installed
#!pip install tweepy
#!pip install textblob
#!python -m textblob.download_corpora

import pandas as pd
import tweepy
from textblob import TextBlob

Configure tweepy API

In [0]:
consumer_key = "xxxxxxx"
consumer_secret = "xxxxx"

access_token = "xxxxx"
access_token_secret = "xxxxx"

Access the tweepy API

In [0]:
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)

Create dataframe to store tweets

In [0]:
tweets_df = pd.DataFrame()

public_tweets = api.search('Trump', lang='en', count=100)
for tweet in public_tweets:
  analysis = TextBlob(tweet.text)
  df_tweet = pd.DataFrame([[tweet.text, analysis.sentiment.polarity, analysis.sentiment.subjectivity]], columns=['tweet', 'polarity', 'subjectivity'])
  tweets_df = tweets_df.append(df_tweet, ignore_index=True)
In [59]:
tweets_df.head()
Out[59]:
tweet polarity subjectivity
0 @BBackerman1 @dave_nunyabuzz @MyStars2211 @tru... 0.000000 0.000000
1 RT @robreiner: Been trying to figure out why T... -0.300000 0.400000
2 If what Trump is doing is right my whole idea ... 0.428571 0.561905
3 Trump Giving the Boot to the Russians?\nAfter ... -0.100000 0.100000
4 RT @GeorgeTakei: The Stormy Daniels story isn'... 0.000000 0.000000
In [60]:
tweets_df.polarity.mean()
Out[60]:
0.03146868686868687
In [61]:
tweets_df.subjectivity.mean()
Out[61]:
0.33532049062049063
In [0]:
import matplotlib.pyplot as plt
In [63]:
plt.scatter(tweets_df.polarity, tweets_df.subjectivity)
Out[63]:
<matplotlib.collections.PathCollection at 0x7fc84ac8f9d0>