2017-12-17 17 views
0

https://github.com/tweepy/tweepy/blob/master/examples/streaming.pyPythonの、私から、次のようなコードを使用していますtweepyストリーム

APIを使用すると、この例のトラック= [「USA」、「カナダ」]で、複数のフィルタ条件を追跡することができます。これは本質的にストリームが「カナダ」または「アメリカ」のいずれかを指すつぶやきを収集することを意味します。

問題は、on_data()関数はデータを出力しますが、データが属するフィルタ用語を指定していないことです。 githubページで提供されているサンプルなどの1つの用語でフィルタリングするときは暗黙的ですが、複数の用語を使用すると、用語とそれに関連付けられたデータの両方をどのように出力できますか?

つまり、「カナダ」と「USa」のどちらでフィルタされたつぶやきを知ることができますか?

from __future__ import absolute_import, print_function 

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

# Go to http://apps.twitter.com and create an app. 
# The consumer key and secret will be generated for you after 
consumer_key="" 
consumer_secret="" 

# After the step above, you will be redirected to your app's page. 
# Create an access token under the the "Your access token" section 
access_token="" 
access_token_secret="" 

class StdOutListener(StreamListener): 
    """ A listener handles tweets that are received from the stream. 
    This is a basic listener that just prints received tweets to stdout. 
    """ 
    def on_data(self, data): 
     print(data) 
     return True 

    def on_error(self, status): 
     print(status) 

if __name__ == '__main__': 
    l = StdOutListener() 
    auth = OAuthHandler(consumer_key, consumer_secret) 
    auth.set_access_token(access_token, access_token_secret) 

    stream = Stream(auth, l) 
stream.filter(track=['usa','canada']) 

答えて

0

あなたは第三の可能性に言及しませんでした:つぶやきは両方「カナダ」と「USA」と一致したことを。それでも解決策は、ツイートにフィルタワードが存在するかどうかをテストすることです。 So:

def on_data(self, data): 
    text = data.text.lower() 
    if "canada" in text: 
     do_canada() 
    if "usa" in text: 
     do_usa() 
    return True 
関連する問題