3

私はPythonだけでなく、プログラミングにもまったく慣れていないので、あなたの助けに感謝します!

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

ユーザーIDでフィルタリングし、ツイートがリアルタイムで収集されていることを確認しました。

ただし、最新のツイートとは対照的に、最後から2番目のツイートのみがリアルタイムで収集されているようです。

助けてもらえますか?

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)
4

2 に答える 2

5

私はこれと同じ問題を抱えていました。私の場合、答えはpythonをバッファなしで実行するほど簡単ではなく、元の投稿者の問題も解決しなかったと思います。問題は、実際には、streaming.pyというファイルのtweepyパッケージのコードと関数_read_loop()にあります。これは、TwitterがストリーミングAPIからデータを出力する形式の変更を反映するように更新する必要があると思います。

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

tweepyクラスの詳細を調べたところ、streaming.pyクラスがjsonツイートストリームを読み取る方法に問題がありました。着信ステータスのビット数を含めるためにストリーミング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ディレクトリに移動し、システムに応じてsudosetup.pyinstallのようなものを入力することで実行されます。

また、このパッケージについてgithubのコーダーにコメントして、問題が発生したことを知らせました。

于 2012-04-29T00:21:54.353 に答える
1

これは、出力バッファリングの場合です。-uこれが起こらないように、(バッファなしで)pythonを実行します。

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

その他のアイデアについては、この回答を参照してください。

于 2012-04-10T07:06:45.860 に答える