LoginSignup
15
14

More than 5 years have passed since last update.

犬派と猫派の勢力図をGoogleChartAPIでグラフ化して決着をつける

Posted at

犬派、猫派の勢力争いを終焉させるべく、ウェブ上で犬と猫どちらが注目されているのか比較するページを作ってみた。

比較くん
http://xiidec.appspot.com/vschart.html?q=犬,猫

結果はこんな感じ。

いぬねこひかく

猫優勢。
過去30日間のはてなブックマーク数を集計してGoogleChartAPIでグラフ化してる。

犬猫以外でも、入力ボックスにカンマ区切りでキーワードを入れると何でも比較できる。

PPR

KH

GEHA

ありとあらゆる宗教戦争が終焉するね!

仕組み

仕組みはとっても単純。

  1. はてなブックマークからキーワードごとのブクマRSSを取ってくる。
  2. ブックマーク数を数える。
  3. Google Chart APIを呼び出すURLを生成してクライアントに渡す。

まず1番目。

はてなブックマークはキーワードごとの新着RSSをを提供してる。

http://b.hatena.ne.jp/search/tag?q=猫&mode=rss

このURLにキーワードを埋め込んでアクセスするだけ。
するとRSSが落ちてくる。

次は2番目。

記事の数では人気度合いを測るのが難しいから、
どれだけブックマークされているかを数える。
XMLの中に

<hatena:bookmarkcount>16</hatena:bookmarkcount>

って項目があるから、それを数える。
ちなみに今回は過去30日以内の記事のみ取ってきてる。
記事の日付を見たければ

<dc:date>2005-12-22T14:40:18+09:00<<dc:date>

ってところを見ればいい。

最後に3番目。

ここで登場Google Chart API。
これも使い方は簡単。

https://chart.googleapis.com/chart?

というURLのあとに

cht=【グラフの種類】

&chs=【グラフの大きさ】

&chd=【グラフのパラメータ】

&chl=【ラベルの名前】

を付加して

https://chart.googleapis.com/chart?cht=p3&chs=400x200&chd=t:48,51&chl=%E7%8A%AC|%E7%8C%AB

こんな感じのURLを作るだけ。

あっという間に完成。
できあがりの品がこちら。

vschart.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import webapp2
import os
import urllib
from google.appengine.ext.webapp import template
from datetime import datetime, timedelta
from xml.etree.ElementTree import *


class VsChart(webapp2.RequestHandler):
    def get(self):
        if self.request.get('q')!="":
            url=self.get_hatebu_chart_url(self.request.get('q').replace(" ",",").split(","))
        else:
            url=""
        q=self.request.get('q')
        template_values={
        'url':url,
        'q':q
        }
        path = os.path.join(os.path.dirname(__file__), 'html/vschart.html')
        self.response.out.write(template.render(path, template_values))

    def count_hatebu_tag(self,q):
        count=0
        ago_30=datetime.today()-timedelta(days=30)
        tree = parse(urllib.urlopen('http://b.hatena.ne.jp/search/tag?q=' + q + '&mode=rss'))
        for i in tree.findall('./{http://purl.org/rss/1.0/}item'):
            if ago_30 <= datetime.strptime(i.find('{http://purl.org/dc/elements/1.1/}date').text.split("T")[0], "%Y-%m-%d"):
                count += int(i.find('{http://www.hatena.ne.jp/info/xmlns#}bookmarkcount').text)
        return count

    def get_hatebu_chart_url(self,qList):
        countList=[]
        allCount=0
        for q in qList:
            count = self.count_hatebu_tag(q.encode("utf-8"))
            allCount+=count
            countList.append(count)
        if allCount != 0:
            perList = [str((c*100 / allCount)) for c in countList]
        else:
            perList = ["0"]*len(qList)
        return "https://chart.googleapis.com/chart?cht=p3&chs=400x200&chd=t:"+",".join(perList)+"&chl="+"|".join(qList)


app = webapp2.WSGIApplication([
    ('/vschart.html', VsChart)
    ], debug=True)
vschart.html
<html>
<head>
</head>
<body style="">
<p>&nbsp;</p>
<p>
<meta charset="UTF-8"></meta>
<title>比較くん</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.js"></script>
<div data-role="page" id="first">
    <div data-role="content">   
        <h1>どっちが人気?</h1>
        <form action="/vschart.html" method="get">
比較対象をカンマ区切りで入れてね。過去一ヶ月間のネット上での注目度合いを比較するよ。
<input type="text" name="q" id="q" size="40" value="{{ q }}"><input type="submit" value="比較する">
        </form>
        <div>
            <img src="{{ url }}" alt="たんぽぽ">
        </div>
</div>
</div>
</body>
</html>

まとめ

今回は円グラフだったけど、棒グラフとか折れ線グラフとか色々ある。
詳しい内容はGoogleのリファレンスページでチェック!

Google Chart Tools:Image Charts (Deprecated)
https://developers.google.com/chart/image/?hl=ja

ん・・・Deprecated?

Important: The Image Charts portion of Google Chart Tools has been officially deprecated as of April 20, 2012. It will continue to work as per our deprecation policy.

重要:Googleのチャートツールの画像チャート部分は正式に2012年4月20日の時点で廃止されました。それは私たちの非推奨ポリシーに従って動作し続けます。

ええーーーーーー
画像を使ったGoogleChartAPIはもう非推奨で、
JavascriptとSVGを使った新しいGoogleChartAPIを使えってことらしい。

せっかく作ったのに・・・

15
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
14