Introduction
こんばんは、はにおかさいです。前回概要を書きましたので、実践のコーナーです。
今回はツイートデータを取得して、それをSQLite3に書き込ませます。
Code
#!/usr/bin/env python
# encoding: utf-8
import datetime
import got
import sqlite3
#username
username = "twitter"
#いくつツイートを取得するか
max = 100
now = datetime.datetime.now()
dbpath = 'tt_{0:%Y%m%d%H%M}'.format(now)+username+".sqlite3"
# データベース接続とカーソル生成
connection = sqlite3.connect(dbpath)
#実行後即座に書き込む
connection.isolation_level = None
cursor = connection.cursor()
#テーブル作成
cursor.execute("CREATE TABLE IF NOT EXISTS tweets (id INTEGER PRIMARY KEY, permalink TEXT, text TEXT, date TEXT, retweets INTEGER, favorites INTEGER , unixtime INTEGER)")
def savesql(v):
try:
# data2 = ["id", "permalink", "text", "date", "retweets", "favorites",(ココマデ) "mentions", "hashtags", "geo"]
unixtime = int(v.date.timestamp())#v.dateはdatetime型です
cursor.execute("INSERT INTO tweets VALUES (?, ?, ?, ?, ?, ?, ?)", (v.id, v.permalink , v.text, v.date, v.retweets, v.favorites, unixtime))
except sqlite3.Error as e:
print(str(e))
tweetCriteria = got.manager.TweetCriteria().setUsername(username=username).setTopTweets(True).setMaxTweets(max)
tweet = got.manager.TweetManager.getTweets(tweetCriteria)
for v in tweet:
savesql(v)
print(v.text)
connection.close()
Result
例:tt_201804010204twitter.sqlite3
確かに取得できます。(自分のテストでは3000件は余裕でした)
Conclusion
この方法の良いところはAPIキーなしでツイートがほぼ無制限に取得できることだと思います。
この手法を活用して、ユーザーの感情分析や複数ユーザーとの共通項を発見し、ツイッターユーザー同士のマッチングサービスを作りたいと思っています。