Skip to content

Instantly share code, notes, and snippets.

@yoneda
Last active September 1, 2017 16:35
Show Gist options
  • Save yoneda/a4e20dfa2d39cdb59b98afbad295587c to your computer and use it in GitHub Desktop.
Save yoneda/a4e20dfa2d39cdb59b98afbad295587c to your computer and use it in GitHub Desktop.
draw graph by tweet time
#coding:utf-8
import json
import requests
import time
import numpy as np
import matplotlib.pyplot as plt
from requests_oauthlib import OAuth1
from datetime import datetime, timedelta
from email.utils import parsedate_tz
def to_datetime(datestring):
time_tuple = parsedate_tz(datestring.strip())
dt = datetime(*time_tuple[:6])
return dt - timedelta(seconds=time_tuple[-1])
def count_hour(count,num):
for key,value in count.items():
if key==num:
value = value + 1
count[key] = value
def main():
# auth認証を作成
f = open("key.json")
data = json.load(f)
f.close()
auth = OAuth1(data["CK"],data["CS"],data["AT"],data["AS"])
# ツイートを取得
url = "https://api.twitter.com/1.1/statuses/user_timeline.json"
params = {"screen_name":"@SatoMasahisa","count":"200"}
response = requests.get(url,params=params,auth=auth)
tweets = response.json()
count = {"0":0,"1":0,"2":0,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0,"13":0,"14":0,"15":0,"16":0,"17":0,"18":0,"19":0,"20":0,"21":0,"22":0,"23":0}
for tweet in tweets:
created_at = tweet["created_at"]
dt = to_datetime(created_at)
hour = dt.hour
count_hour(count,str(hour))
tweetsNums = [value for key,value in count.items()]
# グラフを描画
x = np.arange(0,24)
y = tweetsNums
plt.plot(x,y)
plt.savefig("graph_sato.png")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment