Академический Документы
Профессиональный Документы
Культура Документы
This article covers the sentiment analysis of any topic by parsing the tweets
fetched from Twitter using Python.
Tweepy: tweepy is the python client for the official Twitter API.
Install it using following pip command:
python -m textblob.download_corpora
(Corpora is nothing but a large and structured set of texts.)
Authentication:
In order to fetch tweets through Twitter API, one needs 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:
filter_none
edit
play_arrow
brightness_4
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 = 'XXXXXXXXXXXXXXXXXXXXXXXX'
consumer_secret = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX'
access_token = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX'
access_token_secret = 'XXXXXXXXXXXXXXXXXXXXXXXXX'
# 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")
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 = {}
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)
if __name__ == "__main__":
# calling main function
main()
Here is how a sample output looks like when above program is run:
Positive tweets:
RT @JohnGGalt: Amazing—after years of attacking Donald Trump the media managed
to turn #InaugurationDay into all about themselves.
#MakeAme…
RT @vooda1: CNN Declines to Air White House Press Conference Live YES!
THANK YOU @CNN FOR NOT LEGITIMI…
RT @Muheeb_Shawwa: Donald J. Trump's speech sounded eerily familiar...
POTUS plans new deal for UK as Theresa May to be first foreign leader to meet new
president since inauguration
.@realdonaldtrump #Syria #Mexico #Russia & now #Afghanistan.
Another #DearDonaldTrump Letter worth a read @AJEnglish
Negative tweets:
RT @Slate: Donald Trump’s administration: “Government by the worst men.”
RT @RVAwonk: Trump, Sean Spicer, et al. lie for a reason.
Their lies are not just lies. Their lies are authoritarian propaganda.
RT @KomptonMusic: Me: I hate corn
Donald Trump: I hate corn too
Me: https://t.co/GPgy8R8HB5
It's ridiculous that people are more annoyed at this than Donald Trump's sexism.
RT @tony_broach: Chris Wallace on Fox news right now talking crap
about Donald Trump news conference it seems he can't face the truth eithe…
RT @fravel: With False Claims, Donald Trump Attacks Media on Crowd Turnout
Aziz Ansari Just Hit Donald Trump Hard In An Epic Saturday NIght Live Monologue
We follow these 3 major steps in our program:
First of all, we create a TwitterClient class. This class contains all the methods
to interact with Twitter API and parsing tweets. We use __init__ function to handle
the authentication of API client.
In get_tweets function, we use:
fetched_tweets = self.api.search(q = query, count = count)
to call the Twitter API to fetch tweets.
if analysis.sentiment.polarity > 0:
return 'positive'
elif analysis.sentiment.polarity == 0:
return 'neutral'
else:
return 'negative'
Finally, parsed tweets are returned. Then, we can do various type of statistical
analysis on the tweets. For example, in above program, we tried to find the
percentage of positive, negative and neutral tweets about a query.
References:
http://www.ijcaonline.org/research/volume125/number3/dandrea-2015-ijca-905866.pdf
https://textblob.readthedocs.io/en/dev/quickstart.html#sentiment-analysis
textblob.readthedocs.io/en/dev/_modules/textblob/en/sentiments.html
This article is contributed by Nikhil Kumar. If you like GeeksforGeeks and would
like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.