morris555's diary

高校生のブログです。

pythonでtwitterトレンドを・・・

はじめに

歯医者の待ち時間が暇だったので・・・

お遊び感覚でツイッターのトレンドを取得するものを考えてみました。

今回もtweepyを使いました。

本題

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import tweepy
import sys


def get_oauth():
    consumer_key = ''
    consumer_secret = ''
    access_key = ''
    access_secret = ''

    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_key, access_secret)
    return auth


def get_trends(api, woeid):
    trend = api.trends_location(woeid)[0]
    trends = trend['trends']
    print(u"場所:{0}".format(trend["locations"][0]["name"]))
    print(u"トレンド:")
    for i in range(len(trends)):
        print(u"\t{0}".format(trends[i]["name"]))


def main():
    auth = get_oauth()
    api = tweepy.API(auth_handler=auth)
    if len(sys.argv) >= 2:
        woeid = int(sys.argv[1])
    else:
        woeid = 23424856
    try:
        get_trends(api, woeid)
    except tweepy.error.TweepError:
        print('おそらく指定された場所のデータはありません。')
        exit()


if __name__ == '__main__':
    main()

https://gist.github.com/1610537

引数にwoeidを指定すれば、指定されたところのトレンドが表示されます。

特に指定がない場合は、日本(woeid:23424856)になります。

ちなみに東京のwoeidは1118370です。

おわりに

今回はwoeidを使ってトレンドを取得しましたが、

日本の都市でトレンドが取得できるのは東京だけなので

ぜひたくさんの都市に対応してもらいたいですね。