2016-02-26 72 views
0

我正在嘗試從twitter獲取數據進行處理。請參閱代碼我希望與特定主題相應的特定推文相對應的各種數據。我能夠獲取數據(created_at,text,username,user_id)。它顯示錯誤,當我嘗試獲取(位置,followers_count,friends_count,retweet_count)。獲取與鳴叫相對應的各種數據

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

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

class listener(StreamListener): 

    def on_data(self,data): 
    try: 
     all_data = json.loads(data) 

     tweet = all_data["text"] 

     username = all_data["user"]["screen_name"] 

     timestamp = all_data["created_at"] 

     user_id = all_data["id_str"] 

     location = all_data["location"] 

     followers_count = all_data["followers_count"] 

     friends_count = all_data["friends_count"] 

     retweet_count = all_data["retweet_count"] 

     saveThis = str(time.time())+'::'+timestamp+'::'+username+'::'+user_id+'::'+tweet+'::'+followers_count+'::'+friends_count+'::'+retweet_count+'::'+location 
     saveFile = open('clean2.txt','a') 
     saveFile.write(saveThis) 
     saveFile.write('\n') 
     saveFile.close 
     return True 
    except BaseException, e: 
     print 'failed on data,',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=["tweepy"])#topic 

回答

0

all_data["location"]失敗的原因是,鳴叫不具有這樣的屬性:https://dev.twitter.com/overview/api/tweets

  • 同樣與FRIENDS_COUNT,FOLLOWERS_COUNT - 它們是用戶,而不是推特的性質。

該代碼不應該在all_date["retweet_count"]上失敗,因爲tweets具有這樣的屬性。

P.S.請在報告錯誤時提供錯誤消息(即使您跳過完整的錯誤跟蹤)。使它更容易幫助你,否則你必須猜測錯誤可能是什麼。

+0

感謝它幫了很多。我得到了retweet_count。對於followers_count,我使用了followers_count = str(all_data [「user」] [「followers_count」]),同樣對於其他3 ...... – ravi