備忘録

物忘れが酷いので

tweepyでstreamingを使う

まず、filterを使ってみます

import sys
import tweepy
from tweepy.auth import OAuthHandler
from tweepy.api import API

class myExeption(Exception): pass

class StreamListener(tweepy.streaming.StreamListener):

	def __init__(self):
		#データベースに接続するときなどに使えます
                #↓これを忘れると動きません
		super(StreamListener,self).__init__()

	def __del__(self):
		#データベースを閉じることなどに使えます

	def on_status(self,status):
                
		text = status.text #本文
		date = status.created_at #ツイートされた日時(確かdatetime型)
        name = status.author.name #投稿者id名(unicode型、sqlite3で都合が良いので.encode("utf-8")とはしませんでした
		screen_name = status.author.screen_name #投稿者の名前
                img = status.author.profile_image_url #投稿者のプロファイル画像
"""
その他にもauthorはid,location,followers_count,status_count,description,friends_count,
profile_background_image_url,lang,time_zone,following.favorities_count
などを持っている
"""
		return True

	def on_error(self,status):
		print "can't get"

	def on_timeout(self):
		raise myExeption

def get_oauth():
    consumer_key =  ''
    consumer_secret =  ''
    access_key = ''
    access_secret  = ''
    auth = OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_key, access_secret)
    return auth

if __name__ == '__main__':
	auth = get_oauth()
	stream = tweepy.Stream(auth,StreamListener())
	while True :
		try:
			stream.filter(languages=['ja'],track=['yomiuri','sankei','nikkei'])
		except myExeption() :
                        #twitterに弾かれた場合は少し待って接続し直します
			time.sleep(60)
			stream = tweepy.Stream(auth,StreamListener())

twitterにアプリを登録してキーをもらうには
https://dev.twitter.com/apps

filterは1アカウントに一つしか使えないようです
もし、たくさんのワードで検索したいなら
import re
on_status(self,status)ないで
if re.search(u"hoge",status.text)!=None
とやってstatusの中身を切り分けていくと良いです

ユーザーストリームを使いたい場合は

if __name__ == '__main__':
    auth = get_oauth()

    stream = Stream(auth, StreamListener(), secure=True)


    stream.userstream()

とやれば良いです

初めてのPython 第3版

初めてのPython 第3版

入門 自然言語処理

入門 自然言語処理

パターン認識と機械学習 上

パターン認識と機械学習 上

言語処理のための機械学習入門 (自然言語処理シリーズ)

言語処理のための機械学習入門 (自然言語処理シリーズ)

統計的機械学習―生成モデルに基づくパターン認識 (Tokyo Tech Be‐TEXT)

統計的機械学習―生成モデルに基づくパターン認識 (Tokyo Tech Be‐TEXT)