No science, No life.

もっと科学を身近に

MatlabでTwitterのAPIを使う

MatlabTwitter APIを使ってデータを取得する方法をまとめました。

Twitterのアカウントを持っていない場合は、まずアカウントを作ります。それから、Twitter Platformにアクセスして、APIを使うために必要なキー4種類を取得します。このサイトのお世話になりました。

次に、File ExchangeからtwittyJSON Parserをダウンロードします。このtwittyがスグレモノです。parse_json.mはtwittyのファイル群と同じフォルダに置いておきましょう。

で、Matlabを起動して、twitty.mの説明通りに設定します。まずは、

>> tw = twitty()

と入力します。何か警告が出るかもしれませんが、続けて

>> tw.saveCredentials()

と入力。すると下のようなGUIが登場するので、先ほど取得したキーをコピペします。このキーの入力は1回限りです (Matlabを再起動しても再び入力する必要はない)。

f:id:neocortex:20161228235942p:plain

これで準備完了です!試しに、@MATLABのツイートを取得してみましょう。

>> S = tw.userTimeline('screen_name', 'matlab')

結果は下のようになって、S{1}{インデックス}.textにツイートの内容が格納されます。

>> S

S = 

    {1x20 cell}

>> S{1}{1}

ans = 

                   created_at: 'Wed Dec 28 13:24:16 +0000 2016'
                           id: 8.1410e+17
                       id_str: '814099651293020160'
                         text: 'Get started with MATLAB and #Ardui...'
                    truncated: 0
                     entities: [1x1 struct]
            extended_entities: [1x1 struct]
                       source: '\u003ca href="http://www.hootsuite...'
        in_reply_to_status_id: []
    in_reply_to_status_id_str: []
          in_reply_to_user_id: []
      in_reply_to_user_id_str: []
      in_reply_to_screen_name: []
                         user: [1x1 struct]
                          geo: []
                  coordinates: []
                        place: []
                 contributors: []
              is_quote_status: 0
                retweet_count: 11
               favorite_count: 23
                    favorited: 0
                    retweeted: 0
           possibly_sensitive: 0
                         lang: 'en'

おもなメソッドは、twittyのページに書いてありますし、一覧は下のようにタイプすると得られます。簡単ですね。

>> twitty.API
%% METHODS INTERFACING TWITTER API:            
%% TIMELINES
 homeTimeline()              Returns a collection of the most recent statuses posted by the authenticating user 
 userTimeline()              Returns a collection of the most recent Tweets posted by the user indicated by the
 mentionsTimeline()          Returns the 20 most recent mentions (status containing @username) 
 retweetsOfMe()              Returns the most recent tweets of the authenticated user that have been retweeted
%% STREAMING
 sampleStatuses()            Returns a small random sample of all public statuses via streaming API.
 filterStatuses()            Returns public statuses that match one or more filter predicates.
%% TWEETS
 updateStatus()              Update the authenticating user's status (twit). 
 retweets()                  Returns up to 100 of the first retweets of a given tweet.
 showStatus()                Returns a single status, specified by the id parameter below.
 destroyStatus()             Destroys the status specified by the required ID parameter.
 retweetStatus()             Retweets a tweet specified by the required ID parameter.
 retweeters()                Returns a collection of up to 100 ids of users who retweeted the specified status.
%% SEARCH
 search()                    Search twitter.
%% FRIENDS & FOLLOWERS
 friendsIds()                Returns an array of numeric IDs for every user the specified user is following.
 followersIds()              Returns an array of numeric IDs for every user following the specified user.
 friendshipsLookup()         Returns the relationship of the authenticating user to a list of up to 100
 friendshipsCreate()         Allows the authenticating users to follow the specified user.
 friendshipsDestroy()        Allows the authenticating users to unfollow the specified user.
 friendshipsShow()           Returns detailed information about the relationship between two arbitrary users.
%% USERS
 usersLookup()               Return up to 100 users worth of extended information, specified by either ID, 
 usersShow()                 Returns extended information about a given user.
 usersSearch()               Runs a search for users similar to "Find People" button on Twitter.com.
%% ACCOUNTS
 accountSettings()           Returns settings (including current trend, geo and sleep time information) 
 accountVerifyCredentials()  Test if supplied user credentials are valid.
%% TRENDS
 trendsPlace()               Returns the top 10 trending topics for a specific place (woeid), 
 trendsAvailable()           Returns the locations that Twitter has trending topic information for.
 trendsClosest()             Returns the locations that Twitter has trending topic information for, closest to
%% PLACES & GEO
 geoInfo()                   Returns all the information about a known place.
 geoReverseCode()            Given geographical coordinates, searches for up to 20 places that can be used 
 geoSearch()                 Search for places that can be attached to a statuses/update.
 geoSimilarPlaces()          Locates places near the given coordinates which are similar in name.
%% HELP
 helpConfiguration()         Returns the current configuration used by Twitter including twitter.com slugs 
 helpLanguages()             Returns the list of languages supported by Twitter along with their ISO 639-1 code.
%% THE MAIN API CALLER
 callTwitterAPI()            Call to the twitter API.