2017-12-17 41 views
0

: https://github.com/tweepy/tweepy/blob/master/examples/streaming.py파이썬, 난에서 아래와 같은 코드를 사용하고 tweepy 스트림

API는이 예제 트랙 = [ '미국', '캐나다']에 여러 필터 조건을 추적 할 수 있습니다. 이것은 기본적으로 스트림이 '캐나다'또는 '미국'을 언급하는 트윗을 수집한다는 것을 의미합니다.

on_data() 함수는 데이터를 인쇄하지만 데이터가 속한 필터 용어를 지정하지 않는 것이 문제입니다. github 페이지에 제공된 샘플과 같이 하나의 용어로만 필터를 적용하면 암시 적이지만 여러 용어가있을 때 어떻게 용어와 관련 데이터를 모두 인쇄 할 수 있습니까?

즉, '캐나다'와 '미국'으로 필터링 된 트윗을 어떻게 알 수 있습니까?

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

당신은 세 번째 가능성을 언급하지 않았다 : 트윗은 모두 "캐나다"와 "미국"일치하는 것이다. 그래도 해결 방법은 단순히 필터 단어 중 하나 또는 둘 모두가 트윗에 존재하는지 테스트하는 것입니다. 따라서 :

def on_data(self, data): 
    text = data.text.lower() 
    if "canada" in text: 
     do_canada() 
    if "usa" in text: 
     do_usa() 
    return True