0

私は tweepy に非常に慣れていません. 今のところ, 以下のコードは結果を画面に出力するだけです. しかし, 私がやりたいのは: 各単一の結果を変数に渡すことです:

例えば:

tweet = Twitter().start() 
print tweet
>> justinbieber

だから私の問題は、一度に1つの値を返す方法がわからないことです。

現在、私はこれを持っています。以下のコードは永久に続き、Ctrl + Cを押した後、結果をttに保存しません:

>>> import twitter_streaming_tweepy as t
>>> tt = t.Twitter().start()
alwaysupportjus
Madam_Rauhl

コードは次のとおりです。

import sys
import tweepy

output = []

class CustomStreamListener(tweepy.StreamListener):

    def on_status(self, status):
        try:
            print status.author.screen_name
            output.append(status.author.screen_name)

        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

class Twitter():

    def __init__(self):

        consumer_key="*******"
        consumer_secret="*******"
        access_key = "*******"
        access_secret ="*******"

        self.auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
        self.auth.set_access_token(access_key, access_secret)
        self.api = tweepy.API(self.auth)


    def start(self):
        l = CustomStreamListener()
        stream = tweepy.streaming.Stream(self.auth,l)
        stream.filter(follow=None, track=['justinbieber'])
        return output

if __name__ == "__main__":
    Twitter().start()
4

1 に答える 1

-1

クラス内にtweetという変数を作り、on_statusイベントで受け取ったオブジェクトを変数にthis.tweet = statusで送る。

パフォーマンスのヒントとして、ステータスを 1 つずつ処理すると、プログラムが Twitter から遅延し、Twitter によってストリームが切断されます。ツイートを別のスレッドでバッチとして処理するには、リストまたはキューを使用してください。

楽しんで。

于 2013-04-19T19:05:38.027 に答える