のんびり読書日記

日々の記録をつらつらと

Twitter Streaming APIでデータ収集

Twitterからデータを引っ張ってきたいと前から思ってたので、TwitterStreaming APIを試し中。とりあえず1日分(2010/02/10 12:00 〜 2010/02/11 12:00)のデータを引っ張ってきてみました。ドキュメントはほとんど読んでないままやってるので、いろいろ間違ってるかも。

実際に引っ張ってくるコードはこんな感じ。ユーザ名、TweetのID、日付、Tweetの文面をタブ区切りで出力します。Config::Pitについてはここを参照。

#!/usr/bin/perl

use strict;
use warnings;
use AnyEvent::Twitter::Stream;
use Config::Pit;
use Data::Dumper;
use Encode qw(encode);

my $config = pit_get('twitter.com');
my $method = 'sample';

my $cv = AnyEvent->condvar;
my $listener = AnyEvent::Twitter::Stream->new(
    username => $config->{username},
    password => $config->{password},
    method   => $method,
    #track    => 'google',
    on_tweet => sub {
        my $tweet = shift;
        eval {
            if ($tweet->{id} && $tweet->{user}{screen_name}
                && $tweet->{text} && $tweet->{created_at}) {
                $tweet->{text} = encode 'utf-8', $tweet->{text}
                    if utf8::is_utf8($tweet->{text});
                $tweet->{text} =~ s/\n/ /g;
                printf "%s\t%d\t%s\t%s",
                    $tweet->{user}{screen_name}, $tweet->{id},
                    $tweet->{created_at}, $tweet->{text};
                print "\n";
            }
        };
        if ($@) {
            warn Dumper $@;
#            exit 1;
        }
    },
    on_keepalive => sub {
        warn "ping\n";
    },
    on_eof => $cv,
);
$cv->recv;

1日分のTweetをカウントしてみると下の結果になった。あと各Tweetから何かしら特徴を求めたいので、とりあえず日本語だけに限定して、カタカナ・平仮名・漢字のいずれを含む文章のうち、MeCabで一般名詞か固有名詞がとれるものだけを抽出してみた。中国語も入っちゃってそうだけど、数は少ないと思うので無視で。

- Tweet ファイルサイズ
Tweet 1718239件 225MB
日本語を含むTweet 53537件 9.7MB
日本語で名詞を含むTweet 53195件 9.7MB

Twitterの投稿量が1日で170万件だけってわけないと思うので、かなりの量が省かれちゃってるのかな?実際はどれくらいあるんだろう。

あとオマケで1時間おきのTweetの数をカウントしてみた。

時(日本時間) Tweet
0 88150
1 88423
2 84763
3 82074
4 81279
5 79663
6 81182
7 82106
8 81632
9 83521
10 86534
11 85347
12 79614
13 68669
14 59306
15 49191
16 46703
17 45748
18 46131
19 48526
20 53187
21 62295
22 72542
23 81651
  • 日本語で名詞を含むもの
時(日本時間) Tweet
0 3856
1 2876
2 1856
3 1100
4 705
5 610
6 624
7 930
8 1153
9 1619
10 1972
11 2269
12 2506
13 2286
14 2195
15 2069
16 2310
17 2508
18 2666
19 2666
20 3051
21 3419
22 3830
23 4119

さーて次は実際にTwitterのデータを使って何かつくろう。関連Twitter検索作ろうかな。