Twitter Sentiment Analysis

!pip install tweepy --user
!pip install textblob
import tweepy
from textblob import TextBlob
import matplotlib.pyplot as plt
import pandas as pd

consumerkey = "K5w9ymEECNwXhDSkQmyi9sqoQ"
consumersecret = "V0ZXH9Hd7pv6xUz1Sn3X2fpYvcPiAoKbsxdWMrPw3y89QRIsEy"
accesstoken = "1480744292280795141-3bPehkoHn1JSYYRH7WkSQzRH9Ypbq6"
accesstokensecret = "2hTMVyyMlzzgrz3UTlfeFzGwS38FKE2iUiNQUhbkB97IH"

authenticate = tweepy.OAuthHandler(consumerkey , consumersecret)
authenticate.set_access_token(accesstoken , accesstokensecret)
api = tweepy.API(authenticate)

search = input("Enter a keyword for search: ")
tweetcount = int(input("Enter a number for search count: "))

tweets = api.search_tweets( q = search , count = tweetcount , lang = "en" )
tweets = list( tweets )
len(tweets)

tweets_list = []
tweets_catg = []
pol = []
nu = 0
pos = 0
neg = 0
cnt = 1
for tweet in tweets:
    cnt = cnt +1
    analysis = TextBlob(tweet.text) # here space is replaced by no space and new line is replaced by no lineprint (analysis)
    # strip removes extra space
    tweets_list.append(tweet.text.replace(" ","").replace("\n","").strip())
    pol.append(analysis.sentiment.polarity) #sentiment is libraries inside the text and polarity is library in sentiments
    #analysis.sentiment.subjectivity
    if analysis.sentiment.polarity == 0:
        nu = nu+1
        tweets_catg.append("Neutral")
    elif analysis.sentiment.polarity > 0:
        pos= pos +1
        tweets_catg.append("Positive")
    elif analysis.sentiment.polarity < 0:
        neg = neg +1
        tweets_catg.append("Negative")
        
df= pd.DataFrame(tweets_list)
df.rename(columns={0:"Tweets"},inplace=True)
df["Polarity"]=pol
df["Review category"]=tweets_catg
df

Last updated