Twitter の JSON をテキストに変換

検索結果の json をテキストに変換した. きっとまた使うので残しておく.

import json
from glob import glob
from datetime import datetime, timedelta

txtconv_table = {
    '&lt;': '<',
    '&gt;': '>',
    '&quot;': '"',
    '\r': '',
    '\n': ' '
}

def dtconv(s):
    return (datetime.strptime(s, '%a, %d %b %Y %H:%M:%S +0000') + timedelta(hours = 9)).strftime('%Y-%m-%d %H:%M')

def txtconv(s):
    for k in txtconv_table:
        s = s.replace(k, txtconv_table[k])
    return s.replace('&amp;', '&')

result = []
for filename in glob('search*.json'):
    with open(filename) as f:
        result += ['%s (@%s) %s' % (dtconv(t['created_at']), t['from_user'], txtconv(t['text'])) for t in json.load(f)['results']]

print '\n'.join(sorted(result)).encode('utf-8')