2016-11-23 72 views
1

我想要使用關鍵字「trump」,「clinton」來檢索鳴叫數據。我通常使用Jupyter Notebook來使用Python3。以下是我的代碼,它在我運行單元格時停止。Twitter挖掘使用流式API,python

我插入的代碼之間的一些其它代碼以獲取錯誤,但沒有工作,要麼..

def limit_handled(cursor): 
    while True: 
     try: 
      yield cursor.next() 
     except tweepy.RateLimitError: 
      time.sleep(15 * 60) 

以下均碼。

import tweepy 

# OAuth setup 
consumer_key = '000000000' 
consumer_secret = '000000000' 
access_token = '0000000000' 
access_secret = '000000000' 

auth = tweepy.OAuthHandler(consumer_key, consumer_secret) 
auth.set_access_token(access_token, access_secret) 

api = tweepy.API(auth) 

class MyListener(tweepy.StreamListener): 

    def on_data(self, data): 
     try: 
      with open('tweet_stream.json', 'a') as file: 
       file.write(data) 
       print(data) 
       return True 
     except BaseException as e: 
      print("Error on_data: {}".format(str(e))) 
     return True 


twitter_stream = tweepy.Stream(auth, MyListener()) 
twitter_stream.filter(track=['trump', 'clinton']) 

代碼使用Jupyter筆記本:

+0

哎呀,你*祕密*代碼的截圖。您需要重新生成身份驗證密鑰,因此您不會成爲垃圾郵件機器人。 –

+0

感謝您的評論。我編輯了截圖並重新生成了我的密鑰。 –

回答

0

您需要將api對象傳遞到流對象。嘗試改變行:

twitter_stream = tweepy.Stream(auth, MyListener())

twitter_stream = tweepy.Stream(api, MyListener())