質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

0回答

600閲覧

python のCSV出力について

dotaka0803

総合スコア6

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

0クリップ

投稿2022/09/16 01:04

前提

TwitterAPIをしようしてツイート情報の取得をしようとしています。
サンプルコードを見つけたのですが、CSV出力のやり方が分からずこまっております。

実現したいこと

実行時printによる表示⇒csv出力の実現

該当のソースコード (サンプルコード参照元:http://ailaby.com/twitter_api/#id5_1)

python

1# -*- coding: utf-8 -*- 2 3from requests_oauthlib import OAuth1Session 4import json 5import datetime, time, sys 6from abc import ABCMeta, abstractmethod 7 8CK = '8uYOL8qfRB---------------' # Consumer Key 9CS = 'HFIcvU2nCB----------------------------------------' # Consumer Secret 10AT = '104137178-----------------------------------------' # Access Token 11AS = '4ViVoEMdiH-----------------------------------' # Accesss Token Secert 12 13class TweetsGetter(object): 14 __metaclass__ = ABCMeta 15 16 def __init__(self): 17 self.session = OAuth1Session(CK, CS, AT, AS) 18 19 @abstractmethod 20 def specifyUrlAndParams(self, keyword): 21 ''' 22 呼出し先 URL、パラメータを返す 23 ''' 24 25 @abstractmethod 26 def pickupTweet(self, res_text, includeRetweet): 27 ''' 28 res_text からツイートを取り出し、配列にセットして返却 29 ''' 30 31 @abstractmethod 32 def getLimitContext(self, res_text): 33 ''' 34 回数制限の情報を取得 (起動時) 35 ''' 36 37 def collect(self, total = -1, onlyText = False, includeRetweet = False): 38 ''' 39 ツイート取得を開始する 40 ''' 41 42 #---------------- 43 # 回数制限を確認 44 #---------------- 45 self.checkLimit() 46 47 #---------------- 48 # URL、パラメータ 49 #---------------- 50 url, params = self.specifyUrlAndParams() 51 params['include_rts'] = str(includeRetweet).lower() 52 # include_rts は statuses/user_timeline のパラメータ。search/tweets には無効 53 54 #---------------- 55 # ツイート取得 56 #---------------- 57 cnt = 0 58 unavailableCnt = 0 59 while True: 60 res = self.session.get(url, params = params) 61 if res.status_code == 503: 62 # 503 : Service Unavailable 63 if unavailableCnt > 10: 64 raise Exception('Twitter API error %d' % res.status_code) 65 66 unavailableCnt += 1 67 print ('Service Unavailable 503') 68 self.waitUntilReset(time.mktime(datetime.datetime.now().timetuple()) + 30) 69 continue 70 71 unavailableCnt = 0 72 73 if res.status_code != 200: 74 raise Exception('Twitter API error %d' % res.status_code) 75 76 tweets = self.pickupTweet(json.loads(res.text)) 77 if len(tweets) == 0: 78 # len(tweets) != params['count'] としたいが 79 # count は最大値らしいので判定に使えない。 80 # ⇒ "== 0" にする 81 # https://dev.twitter.com/discussions/7513 82 break 83 84 for tweet in tweets: 85 if (('retweeted_status' in tweet) and (includeRetweet is False)): 86 pass 87 else: 88 if onlyText is True: 89 yield tweet['text'] 90 else: 91 yield tweet 92 93 cnt += 1 94 if cnt % 100 == 0: 95 print ('%d件 ' % cnt) 96 97 if total > 0 and cnt >= total: 98 return 99 100 params['max_id'] = tweet['id'] - 1 101 102 # ヘッダ確認 (回数制限) 103 # X-Rate-Limit-Remaining が入ってないことが稀にあるのでチェック 104 if ('X-Rate-Limit-Remaining' in res.headers and 'X-Rate-Limit-Reset' in res.headers): 105 if (int(res.headers['X-Rate-Limit-Remaining']) == 0): 106 self.waitUntilReset(int(res.headers['X-Rate-Limit-Reset'])) 107 self.checkLimit() 108 else: 109 print ('not found - X-Rate-Limit-Remaining or X-Rate-Limit-Reset') 110 self.checkLimit() 111 112 def checkLimit(self): 113 ''' 114 回数制限を問合せ、アクセス可能になるまで wait する 115 ''' 116 unavailableCnt = 0 117 while True: 118 url = "https://api.twitter.com/1.1/application/rate_limit_status.json" 119 res = self.session.get(url) 120 121 if res.status_code == 503: 122 # 503 : Service Unavailable 123 if unavailableCnt > 10: 124 raise Exception('Twitter API error %d' % res.status_code) 125 126 unavailableCnt += 1 127 print ('Service Unavailable 503') 128 self.waitUntilReset(time.mktime(datetime.datetime.now().timetuple()) + 30) 129 continue 130 131 unavailableCnt = 0 132 133 if res.status_code != 200: 134 raise Exception('Twitter API error %d' % res.status_code) 135 136 remaining, reset = self.getLimitContext(json.loads(res.text)) 137 if (remaining == 0): 138 self.waitUntilReset(reset) 139 else: 140 break 141 142 def waitUntilReset(self, reset): 143 ''' 144 reset 時刻まで sleep 145 ''' 146 seconds = reset - time.mktime(datetime.datetime.now().timetuple()) 147 seconds = max(seconds, 0) 148 print ('\n =====================') 149 print (' == waiting %d sec ==' % seconds) 150 print (' =====================') 151 sys.stdout.flush() 152 time.sleep(seconds + 10) # 念のため + 10 秒 153 154 @staticmethod 155 def bySearch(keyword): 156 return TweetsGetterBySearch(keyword) 157 158 @staticmethod 159 def byUser(screen_name): 160 return TweetsGetterByUser(screen_name) 161 162 163class TweetsGetterBySearch(TweetsGetter): 164 ''' 165 キーワードでツイートを検索 166 ''' 167 def __init__(self, keyword): 168 super(TweetsGetterBySearch, self).__init__() 169 self.keyword = keyword 170 171 def specifyUrlAndParams(self): 172 ''' 173 呼出し先 URL、パラメータを返す 174 ''' 175 url = 'https://api.twitter.com/1.1/search/tweets.json' 176 params = {'q':self.keyword, 'count':100} 177 return url, params 178 179 def pickupTweet(self, res_text): 180 ''' 181 res_text からツイートを取り出し、配列にセットして返却 182 ''' 183 results = [] 184 for tweet in res_text['statuses']: 185 results.append(tweet) 186 187 return results 188 189 def getLimitContext(self, res_text): 190 ''' 191 回数制限の情報を取得 (起動時) 192 ''' 193 remaining = res_text['resources']['search']['/search/tweets']['remaining'] 194 reset = res_text['resources']['search']['/search/tweets']['reset'] 195 196 return int(remaining), int(reset) 197 198 199class TweetsGetterByUser(TweetsGetter): 200 ''' 201 ユーザーを指定してツイートを取得 202 ''' 203 def __init__(self, screen_name): 204 super(TweetsGetterByUser, self).__init__() 205 self.screen_name = screen_name 206 207 def specifyUrlAndParams(self): 208 ''' 209 呼出し先 URL、パラメータを返す 210 ''' 211 url = 'https://api.twitter.com/1.1/statuses/user_timeline.json' 212 params = {'screen_name':self.screen_name, 'count':200} 213 return url, params 214 215 def pickupTweet(self, res_text): 216 ''' 217 res_text からツイートを取り出し、配列にセットして返却 218 ''' 219 results = [] 220 for tweet in res_text: 221 results.append(tweet) 222 223 return results 224 225 def getLimitContext(self, res_text): 226 ''' 227 回数制限の情報を取得 (起動時) 228 ''' 229 remaining = res_text['resources']['statuses']['/statuses/user_timeline']['remaining'] 230 reset = res_text['resources']['statuses']['/statuses/user_timeline']['reset'] 231 232 return int(remaining), int(reset) 233 234 235if __name__ == '__main__': 236 237 # キーワードで取得 238 getter = TweetsGetter.bySearch(u'渋谷') 239 240 # ユーザーを指定して取得 (screen_name) 241 #getter = TweetsGetter.byUser('AbeShinzo') 242 243 cnt = 0 244 for tweet in getter.collect(total = 3000): 245 cnt += 1 246 print ('------ %d' % cnt) 247 print ('{} {} {}'.format(tweet['id'], tweet['created_at'], '@'+tweet['user']['screen_name'])) 248 print (tweet['text']) 249 #

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

shiracamus

2022/09/16 04:50 編集

まずは自分で、適当なデータをcsvファイルに出力する処理を書いてみませんか? そうすれば、何をすればいいのか見えてきますよ。
meg_

2022/09/16 10:46

調べたことや試したことは何もありませんか?
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだ回答がついていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問