OCJP

Python Code to Get UTF-8 Live Streaming from Twitter

As There are so many methods to get the Tweets using Python Code. Here is the example to get the Tweets using Streaming and Save the tweets to file. Here UTF-8 encoding also done so that Hindi Tweets or tweets in regional languages can be read.

import sys
import tweepy  
import simplejson as json
import codecs


if sys.version_info[0] < 3:
   input = raw_input


# Twitter App access keys for @user
# Consume:
ckey    = 'YOUR_CLIENT_KEY'
csecret = 'YOUR_CLIENT_SECRET'

# Access:
atoken  = 'YOUR_ACCESS_TOKEN'
asecret = 'YOUR_ACCESS_SECRET'

class listener(tweepy.StreamListener):
   x=0
   def on_data(self, data):
      
      try:
         all_data = json.loads(data)
         tweet = all_data["text"]
         username = all_data["user"]["screen_name"]
         out = codecs.open('out1.txt','a', 'utf-8')
         out.write(str(tweet.encode('unicode-escape').decode()))
         out.write('\n')
         out.close()
         encoded = tweet.encode("utf-8", errors='ignore').decode('UTF-8')
         print (username, " :: ", encoded)
         self.x+=1
         if(self.x>10):
            exit(0)
      finally:
         pass
      return True

   def on_error(self, status):
      print (status)

auth = tweepy.OAuthHandler(ckey, csecret)
auth.set_access_token(atoken, asecret)
query = input("What subject do you want to analyze? \n")
keywords = [query]
twitterStream = tweepy.Stream(auth, listener())
try:
   twitterStream.filter(track=keywords)
finally:
   pass

Leave a Reply

Your email address will not be published. Required fields are marked *


× How can I help you?