2012-04-10 17 views
3

私はPythonだけでなくプログラミングにも慣れています。tweepyでストリーミングしているapiは、最後の2番目のツイートだけを返します。

Tweepyを使用して、TwitterのストリーミングAPIからすべてのツイートをフィルタリングしようとしています。

私はユーザーIDでフィルタして、つぶやきがリアルタイムで収集されていることを確認しました。

もつとも、非常に最新のつぶやきとは対照的に、唯一の最後から二番目つぶやきをリアルタイムに収集されているようです。

お手伝いできますか?

import tweepy 
import webbrowser 
import time 
import sys 

consumer_key = 'xyz' 
consumer_secret = 'zyx' 


## Getting access key and secret 
auth = tweepy.OAuthHandler(consumer_key, consumer_secret) 
auth_url = auth.get_authorization_url() 
print 'From your browser, please click AUTHORIZE APP and then copy the unique PIN: ' 
webbrowser.open(auth_url) 
verifier = raw_input('PIN: ').strip() 
auth.get_access_token(verifier) 
access_key = auth.access_token.key 
access_secret = auth.access_token.secret 


## Authorizing account privileges 
auth.set_access_token(access_key, access_secret) 


## Get the local time 
localtime = time.asctime(time.localtime(time.time())) 


## Status changes 
api = tweepy.API(auth) 
api.update_status('It worked - Current time is %s' % localtime) 
print 'It worked - now go check your status!' 


## Filtering the firehose 
user = [] 
print 'Follow tweets from which user ID?' 
handle = raw_input(">") 
user.append(handle) 

keywords = [] 
print 'What keywords do you want to track? Separate with commas.' 
key = raw_input(">") 
keywords.append(key) 

class CustomStreamListener(tweepy.StreamListener): 

    def on_status(self, status): 

     # We'll simply print some values in a tab-delimited format 
     # suitable for capturing to a flat file but you could opt 
     # store them elsewhere, retweet select statuses, etc. 



     try: 
      print "%s\t%s\t%s\t%s" % (status.text, 
             status.author.screen_name, 
             status.created_at, 
             status.source,) 
     except Exception, e: 
      print >> sys.stderr, 'Encountered Exception:', e 
      pass 

    def on_error(self, status_code): 
     print >> sys.stderr, 'Encountered error with status code:', status_code 
     return True # Don't kill the stream 

    def on_timeout(self): 
     print >> sys.stderr, 'Timeout...' 
     return True # Don't kill the stream 

# Create a streaming API and set a timeout value of ??? seconds. 

streaming_api = tweepy.streaming.Stream(auth, CustomStreamListener(), timeout=None) 

# Optionally filter the statuses you want to track by providing a list 
# of users to "follow". 

print >> sys.stderr, "Filtering public timeline for %s" % keywords 

streaming_api.filter(follow=handle, track=keywords) 

答えて

5

この同じ問題がありました。その答えは、私の場合はPythonを実行していないほど簡単ではありませんでした。私は元のポスターの問題も解決していないと推測します。この問題は、streaming.pyという名前のファイルのtweepyパッケージのコードと、streaming APIからデータを出力するフォーマットの変更を反映するために更新する必要がある_read_loop()という関数にあります。

私の解決策は、githubからtweepyの最新コード、https://github.com/tweepy/tweepy、特にstreaming.pyファイルをダウンロードすることでした。最近行われた変更を表示して、このファイルのコミット履歴でこの問題を解決することができます。

tweepyクラスの詳細を調べましたが、streaming.pyクラスがjson tweetストリームで読み取る方法に問題がありました。私はそれが入っている状態のビットの数を含めるために彼らのストリーミングAPIを更新しているTwitterと関係していると思う。短いストーリー、ここでは、この問題を解決するためにstreaming.pyで置き換えた関数がありました。

def _read_loop(self, resp): 

    while self.running and not resp.isclosed(): 

     # Note: keep-alive newlines might be inserted before each length value. 
     # read until we get a digit... 
     c = '\n' 
     while c == '\n' and self.running and not resp.isclosed(): 
      c = resp.read(1) 
     delimited_string = c 

     # read rest of delimiter length.. 
     d = '' 
     while d != '\n' and self.running and not resp.isclosed(): 
      d = resp.read(1) 
      delimited_string += d 

     try: 
      int_to_read = int(delimited_string) 
      next_status_obj = resp.read(int_to_read) 
      # print 'status_object = %s' % next_status_obj 
      self._data(next_status_obj) 
     except ValueError: 
      pass 

    if resp.isclosed(): 
     self.on_closed(resp) 

また、このソリューションは、tweepyパッケージのソースコードをダウンロードする方法を学ぶことを修正し、その後のpythonに変更し、ライブラリをインストールする必要があります。これは、最上位のtweepyディレクトリに入り、あなたのシステムに応じてsudo setup.py installのようなものを入力することによって行われます。

また、このパッケージのgithubのコーダーに、whats upを知らせるためのコメントをしました。

+3

私は自分のレポをフォークし、この修正を加えました。プルリクエストを待っています。当分の間、ここで固定バージョンを入手できます:https://github.com/robbrit/tweepy – robbrit

+0

@robbrit - ありがとう!私は本当にこれを感謝します。まだプルされていますか? – snakesNbronies

1

これは出力バッファリングのケースです。これを防ぐためにpythonを-u(unbuffered)で実行してください。

または、print文の後にsys.stdout.flush()を実行して、強制的にバッファをフラッシュすることができます。

詳細については、this answerを参照してください。

+0

ありがとうございます!私はそれがマイナーなものであることを知っていた。 – snakesNbronies

関連する問題