ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Twitter Hashtag Sentiment Analysis] (2) 파이썬 스트리밍 API를 이용해 트윗 가져오기
    취미로 하는 프로젝트 2019. 7. 14. 08:38


    이전 포스트([Twitter Hashtag Sentiment Analysis] (1) 프로젝트 소개 및 트위터 개발자/앱 등록하기)에서 Consumer API키와 Access Token을 생성했다. 이번 포스트에서는 키를 이용해 실제 스트리밍 해본다.

    Tweepy를 이용한 스트리밍 파이썬 스크립트

    Tweepy는 트위터 API를 사용하기 위한 파이썬 라이브러리이다. Tweepy가 없다면 스트리밍 부분까지 전부 구현해야 하지만 다행히 라이브러리가 있으므로 라이브러리를 이용해 개발 시간을 단축할 수 있었다. Tweepy에 대한 자세한 내용은 https://www.tweepy.org/ 에서 확인 할 수 있다.

    Tweepy 설치

    pip install tweepy

    Tweepy는 pip install tweepy를 이용해 설치 할 수 있다. 만약 파이참 + 파이썬 가상 환경(venv)를 사용한다면 가상환경 안에서 설치하면 된다.

    스트리밍 스크립트

    # Import tweepy library
    from tweepy.streaming import StreamListener
    from tweepy import OAuthHandler
    from tweepy import Stream
    import json

    # 트위터 API 크레덴셜
    access_token = "<TWITTER_ACCESS_TOKEN>"
    access_token_secret = "<TWITTER_ACCESS_TOKEN_SECRET>"
    consumer_key = "<TWITTER_CONSUMER_KEY>"
    consumer_secret = "<TWITTER_CONSUMER_SECRET>"

    # 리스너 - 스트리밍 API로 부터 값이 들어오면 아래의 리스너가 실행된다.
    class Listener(StreamListener):

    def on_data(self, data):
    json_data = json.loads(data)
    print(json_data)
    return True

    def on_error(self, status):
    print("ERROR: " + str(status))


    def main():
    # 리스너 생성
    l = Listener()
    auth = OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    stream = Stream(auth, l) #리스너와 크레덴셜을 Stream클래스 생성시 넘겨준다

    # 언어=한국어(ko), 해시태그=삐멜
    stream.filter(languages=["ko"], track=['삐멜'])


    if __name__ == '__main__':
    main()

    main()

    Stream - 트위터 스트리밍 API 클래스.

    filter - filter의 인자로 language와 track을 넣어준다. track에 스티리밍받을 해시태그를 넣는다.

    Listener - Stream오브젝트 생성시 Listener오브젝트를 넘겨주는데, 이 오브젝트의 on_data와 on_error는 콜백 함수로, 스트리밍 데이터를 받는경우 on_data, 에러가 나는 경우 on_error가 실행된다.

    stream.filter가 불리는 순간 스트리밍이 시작된다. 

    실행결과

    데모를 위해 코드 실행 후 트위터에 글을 올렸다.

    콘솔을 통해 받은 스트리밍 결과

    {'created_at': 'Sat Jul 13 23:20:58 +0000 2019', 'id': 1150183366425075712, 'id_str': '1150183366425075712', 'text': '트위터 해시태그 스트리밍 포스팅용 데모\n#삐멜', 'source': '<a href="http://twitter.com" rel="nofollow">Twitter Web Client</a>', 'truncated': False, 'in_reply_to_status_id': None, 'in_reply_to_status_id_str': None, 'in_reply_to_user_id': None, 'in_reply_to_user_id_str': None, 'in_reply_to_screen_name': None, 'user': {'id': 1087578285200965632, 'id_str': '1087578285200965632', 'name': '삐멜', 'screen_name': 'fsoftwareengin1', 'location': None, 'url': 'http://imasoftwareengineer.tistory.com', 'description': '실리콘밸리의 여성 소프트웨어 엔지니어입니다. \n주로 블로그 관련, 컴퓨터 관련 트윗 합니다. \n아무거나 트윗합니다. \n가끔 하는 개인적인 이야기는 조언이나 독려가 아닙니다.\n제 트윗은 회사의 의견을 반영하지 않습니다.', 'translator_type': 'none', 'protected': False, 'verified': False, 'followers_count': 2154, 'friends_count': 46, 'listed_count': 16, 'favourites_count': 429, 'statuses_count': 438, 'created_at': 'Tue Jan 22 05:10:44 +0000 2019', 'utc_offset': None, 'time_zone': None, 'geo_enabled': False, 'lang': None, 'contributors_enabled': False, 'is_translator': False, 'profile_background_color': '000000', 'profile_background_image_url': 'http://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_image_url_https': 'https://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_tile': False, 'profile_link_color': '19CF86', 'profile_sidebar_border_color': '000000', 'profile_sidebar_fill_color': '000000', 'profile_text_color': '000000', 'profile_use_background_image': False, 'profile_image_url': 'http://pbs.twimg.com/profile_images/1089407187661729792/Y4yt7x3q_normal.jpg', 'profile_image_url_https': 'https://pbs.twimg.com/profile_images/1089407187661729792/Y4yt7x3q_normal.jpg', 'profile_banner_url': 'https://pbs.twimg.com/profile_banners/1087578285200965632/1548570710', 'default_profile': False, 'default_profile_image': False, 'following': None, 'follow_request_sent': None, 'notifications': None}, 'geo': None, 'coordinates': None, 'place': None, 'contributors': None, 'is_quote_status': False, 'quote_count': 0, 'reply_count': 0, 'retweet_count': 0, 'favorite_count': 0, 'entities': {'hashtags': [{'text': '삐멜', 'indices': [22, 25]}], 'urls': [], 'user_mentions': [], 'symbols': []}, 'favorited': False, 'retweeted': False, 'filter_level': 'low', 'lang': 'ko', 'timestamp_ms': '1563060058586'}


    다음 포스트에서는 Amazon Kinesis Firehose를 셋업, boto3 설치 및 위의 스크립트를 이용해 Firehose로 스트리밍 데이터를 전송하는 법을 설명할 것이다.

    댓글

f.software engineer @ All Right Reserved