Twitterの流量を計算してみよう

30分プログラム、その673。Twitterの流量を計算してみました。
Twitterには"流量"という概念があるらしいです。よく分かんないんですが、「自分のTLで、1時間あたり何回発言が行なわれたか」というニュアンスみたいです。
わりとおもしろそうなネタなので、自分で計算してみましょう。

アプローチ

まずTLを取得する必要があります。Twitterクライアントに組込むとか、APIを叩いて自分のTLを取得するとかも、いろいろな方法があると思います。
でも、そういうのだと1時間分のTLを取得するのが面倒そうだっあので、tig.rb×tiarraでとり続けてるログを利用してみました。tig.rbとtiarraレンタルサーバ上でずっと動かしつづけてるので、取得できた発言が全て記録されてます。
ログは日付ごとに、別のファイルに保存されて、それぞれ以下のような形式になってます。

23:57:19 <#twitter@t:@nobio0205> 一方俺はフレイバーテキ.....
23:57:19 <#twitter@t:@hi_saito> AWK Users JP :: 日本の AWK ユーザ...
...

ちなみに、tig.rb×tiarraの設定はTwitterもMSNもIRCにまとめちゃう - みずぴー日記で説明してます。

使い方

とりあえず使ってみましょう。

$ python tl-speed.py 2009.10.02.txt
2009.10.02.txt
[00:__:__] 265
[01:__:__] 172
[02:__:__] 107
[03:__:__] 121
[04:__:__] 30
[05:__:__] 45
[06:__:__] 55
[07:__:__] 48
[08:__:__] 67
[09:__:__] 112
[10:__:__] 91
[11:__:__] 125
[12:__:__] 141
[13:__:__] 188
[14:__:__] 155
[15:__:__] 174
[16:__:__] 185
[17:__:__] 165
[18:__:__] 156
[19:__:__] 185
[20:__:__] 180
[21:__:__] 160
[22:__:__] 237
[23:__:__] 218

昼夜を問わずコンスタントな流量があるけれども、朝だけは弱い、という結果になりました。ボクの直感とも合致してます。

ソースコード

#! /usr/bin/python
# -*- mode:python; coding:utf-8 -*-
#
# tl-speed.py -
#
# Copyright(C) 2009 by mzp
# Author: MIZUNO Hiroki / mzpppp at gmail dot com
# http://howdyworld.org
#
# Timestamp: 2009/10/06 20:57:01
#
# This program is free software; you can redistribute it and/or
# modify it under MIT Lincence.
#
from __future__ import with_statement
import re
import sys

def filter_map(f,xs):
    for x in xs:
        y = f(x)
        if y:
            yield y

# e.g. 08:15:48 <#twitter@t:@scheme_abc> ....
Line = re.compile(r"(\d\d:\d\d:\d\d) <#twitter@t")

def parse(l):
    m = Line.match(l)
    if m:
        return m.group(1).split(":")
    else:
        return None

def speed(xs):
    count = [0] * 24
    for (hour,_,_) in xs:
        count[int(hour)] += 1
    return count

def show(xs):
    for (i,x) in zip(xrange(0,len(xs)),xs):
        print "[%02d:__:__] %d" % (i,x)

for path in sys.argv[1:]:
    print path
    with open(path) as f:
        show(speed(filter_map(parse,f)))