【问题标题】:except BaseException as e: keeps throwing an error除了 BaseException as e: 不断抛出错误
【发布时间】:2019-05-04 19:34:26
【问题描述】:

我正在学习有关分析 Twitter 数据的教程。我想知道为什么我在第 44 行不断收到语法错误:除了 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)

【问题讨论】:

    标签: python api tweepy twitter-streaming-api


    【解决方案1】:

    您的except 缩进太多。应与try (在on_data() 中)处于同一级别,并且except 中的代码应缩进相同。

    顺便说一句,函数写错了。在某些情况下,它什么也不返回。您应该至少在函数体的末尾添加return False

    【讨论】:

      【解决方案2】:

      Except应该缩进为try,所以试试下面的

      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
      

      【讨论】:

        猜你喜欢
        • 2021-10-06
        • 2010-10-11
        • 2015-04-07
        • 2022-09-29
        • 1970-01-01
        • 2017-11-11
        • 2016-09-09
        • 2017-09-24
        • 1970-01-01
        相关资源
        最近更新 更多