skip to Main Content

I’m following a tutorial about analyzing twitter data. I’m wondering why I keep getting a syntax error on line 44: except BaseException as e:

from tweepy import API
from tweepy import Cursor
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream

import twitter_credentials
#TWITTER AUTHENTICATOR
class TwitterAuthenticator():

    def authenticate_twitter_app(self):
        auth = OAuthHandler(twitter_credentials.CONSUMER_KEY, twitter_credentials.CONSUMER_SECRET)
        auth.set_access_token(twitter_credentials.ACCESS_TOKEN, twitter_credentials.ACCESS_TOKEN_SECRET)
        return auth

#TWITTER STREAMER
class TwitterStreamer():

#Class for streaming and processing live tweets
    def __init__(self):
        self.twitter_authenticator = TwitterAuthenticator()


    def stream_tweets(self, fetched_tweets_filename, hash_tag_list):
        #This handles Twitter authentication and connection to the Twitter streaming API
        listener = TwitterListener()
        auth = self.twitter_authenticator.authenticate_twitter_app()
        stream = Stream(auth, listener)

        stream.filter(track=hash_tag_list)

class TwitterListener(StreamListener):
#Basic listener class that just prints received tweets to stdout
    def __init__(self, fetched_tweets_filename):
        self.fetched_tweets_filename = fetched_tweets_filename


    def on_data(self, data):
        try:
            print(data)
            with open(self.fetched_tweets_filename, 'a') as tf:
                tf.write(data)
                return True
            except BaseException as e:
                    print('Error on_data %s' % str(e))
                return True

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


if __name__ == '__main__':

    hash_tag_list['kevin durant', 'steph curry', 'clippers']
    fetched_tweets_filename = 'tweets.json'

    twitter_streamer = TwitterStreamer()
    twitter_streamer.stream_tweets(fetched_tweets_filename, hash_tag_list)

2

Answers


  1. Your except is indented too much. Should be on the same level as try (in on_data()) and the code in except should be indented the same.

    Btw said function is written wrong. There are potential cases where it returns nothing. You should have at least return False added at the end of function body.

    Login or Signup to reply.
  2. Except should be indented as try, so try the following

    def on_data(self, data):
        try:
            print(data)
            with open(self.fetched_tweets_filename, 'a') as tf:
                tf.write(data)
                return True
        except BaseException as e:
            print('Error on_data %s' % str(e))
            return True
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search