Wednesday, 8 June 2016

How to download tweets specific to a topic.

Downloading tweets & saving it in a CSV file.

We are using the python programming language to download tweets.
i.e python 2.7 version.

We prefer using Enthought Canopy IDE for executing the code.
Enthought Canopy has valuable tools for iterative data analysis, visualization, and application development.
you don't have to install python software separately as Canopy itself installs it. It has some cool stuff too.
follow this link to download canopy


python code for downloading tweets on a topic.


from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
import time
import json

#replace your twitter API keys here.

ckey = '**************************'
csecret = '**************************'
atoken = '**************************'
asecret = '**************************'

class listener(StreamListener):

    def on_data(self, data):
        try:
            tweet = data.split(',"text":"')[1].split(',"source')[0]
            print tweet
            saveFile = open('tweetsonly.csv','a')
            saveFile.write(tweet)
            saveFile.write('\n')
            saveFile.close()
            return True
        
        except BaseException,e:
            print 'failed ondata ',str(e)
            time.sleep(5)

    def on_error(self, status):
        print status

auth = OAuthHandler(ckey,csecret)
auth.set_access_token(atoken,asecret)
twitterStream = Stream(auth,listener())
twitterStream.filter(track=["@INCIndia","IndianNationalCongress","@Indianpolity","@Election_in","@wbpcc", "#indian elections"])




In the above code, we are downloading tweets related to a political party INC ( Indian National Congress ).
If you want to download tweets on any other topic or the currently trending topic on twitter, you just have to replace the track keywords with the corresponding twitter handles & hashtags.

finally, the tweets are collected & stored in a CSV file on your system.


No comments:

Post a Comment