teratail header banner
teratail header banner
質問するログイン新規登録

質問編集履歴

3

いただいた回答から修正を加え、コードを書き直した

2020/09/14 08:31

投稿

naochan1027
naochan1027

スコア2

title CHANGED
File without changes
body CHANGED
@@ -169,4 +169,75 @@
169
169
 
170
170
  ### 補足情報(FW/ツールのバージョンなど)
171
171
  Jupiterで実行しています。
172
- どなたか力をお貸しください。
172
+ どなたか力をお貸しください。
173
+
174
+ 以下jeanbiego様が回答してくださったものから修正したverです。
175
+ 変更したdef search_tweetsの所のみ掲載します。
176
+
177
+ ```python
178
+ def search_tweets(CK, CKS, AT, ATS, user_id, tweet_id, count, range):
179
+ # 文字列設定
180
+ user_id += ' exclude:retweets' # RTは除く
181
+ user_id = urllib.parse.quote_plus(user_id)
182
+ # リクエスト
183
+ url = "https://api.twitter.com/1.1/search/tweets.json?lang=ja&q="+user_id+"&count="+str(count)
184
+ auth = OAuth1(CK, CKS, AT, ATS)
185
+ response = requests.get(url, auth=auth)
186
+ data = response.json()['statuses']
187
+ # 2回目以降のリクエスト
188
+ cnt = 0
189
+ reply_cnt = 0
190
+ tweets = []
191
+ while True:
192
+ if len(data) == 0:
193
+ break
194
+ cnt += 1
195
+ if cnt > range:
196
+ break
197
+ for tweet in data:
198
+ if tweet['in_reply_to_status_id_str'] == tweet_id: # ツイートIDに一致するものを抽出
199
+ tweets.append([tweet['id_str']])#ツイートID
200
+ tweets.append(['{0:%Y-%m-%d %H:%M:%S}'.format(datetime.strptime(tweet['created_at'], "%a %b %d %H:%M:%S %z %Y") + timedelta(hours=9))])# 投稿日
201
+ tweets.append([tweet['user']['name']])# ユーザー名
202
+ tweets.append([tweet['user']['id_str']])# ユーザーID
203
+ tweets.append([tweet['user']['screen_name']])# ユーザー表示名
204
+ tweets.append([tweet['text']]) # ツイート内容
205
+
206
+ reply_cnt += 1
207
+
208
+ maxid = int(tweet["id"]) - 1
209
+
210
+ url = "https://api.twitter.com/1.1/search/tweets.json?lang=ja&q="+user_id+"&count="+str(count)+"&max_id="+str(maxid)
211
+ response = requests.get(url, auth=auth)
212
+
213
+ try:
214
+ data = response.json()['statuses']
215
+ except KeyError: # リクエスト回数が上限に達した場合のデータのエラー処理
216
+ print('上限まで検索しました')
217
+ break
218
+
219
+ df = pd.DataFrame([tweets],columns=['TweetID',
220
+ 'PostedTime',
221
+ 'UserName',
222
+ 'UserID',
223
+ 'UserScreenName',
224
+ 'PostMessage'])
225
+
226
+ df.to_csv('jr1.csv', encoding="utf-8") # CSV形式で保存
227
+ print('検索回数 :', cnt)
228
+ print('リプライ数 :', reply_cnt)
229
+ print(df)
230
+
231
+ return tweets
232
+
233
+ ```
234
+ エラー文です。tweetsの中に横並びで324個のデータが入ってしまっているようです。
235
+ 全文載せようとしましたが字数制限にひっかかってしまいました。
236
+
237
+ ```エラー
238
+
239
+
240
+ ValueError: 6 columns passed, passed data had 324 columns
241
+ ```
242
+
243
+ 何度も申し訳ありません。分かる方がいらっしゃればよろしくお願いいたします。

2

エラー文の修正

2020/09/14 08:31

投稿

naochan1027
naochan1027

スコア2

title CHANGED
File without changes
body CHANGED
@@ -7,7 +7,73 @@
7
7
  ### 発生している問題・エラーメッセージ
8
8
 
9
9
  ```
10
+ ValueError Traceback (most recent call last)
11
+ ~/opt/anaconda3/lib/python3.7/site-packages/pandas/core/internals/managers.py in create_block_manager_from_blocks(blocks, axes)
12
+ 1661 blocks = [
13
+ -> 1662 make_block(values=blocks[0], placement=slice(0, len(axes[0])))
14
+ 1663 ]
15
+
16
+ ~/opt/anaconda3/lib/python3.7/site-packages/pandas/core/internals/blocks.py in make_block(values, placement, klass, ndim, dtype)
17
+ 2713
18
+ -> 2714 return klass(values, ndim=ndim, placement=placement)
19
+ 2715
20
+
21
+ ~/opt/anaconda3/lib/python3.7/site-packages/pandas/core/internals/blocks.py in __init__(self, values, placement, ndim)
22
+ 2369
23
+ -> 2370 super().__init__(values, ndim=ndim, placement=placement)
24
+ 2371
25
+
26
+ ~/opt/anaconda3/lib/python3.7/site-packages/pandas/core/internals/blocks.py in __init__(self, values, placement, ndim)
27
+ 129 raise ValueError(
28
+ --> 130 f"Wrong number of items passed {len(self.values)}, "
29
+ 131 f"placement implies {len(self.mgr_locs)}"
30
+
31
+ ValueError: Wrong number of items passed 1, placement implies 6
32
+
33
+ During handling of the above exception, another exception occurred:
34
+
35
+ ValueError Traceback (most recent call last)
36
+ <ipython-input-78-0f418a9fed69> in <module>
37
+ 1 if __name__ == '__main__':
38
+ ----> 2 main()
39
+
40
+ <ipython-input-61-f197ee9a00ff> in main()
41
+ 13 range = 100 # 検索回数の上限値(最大180/15分でリセット)
42
+ 14 # ツイート検索・リプライの抽出
43
+ ---> 15 tweets = search_tweets(CK, CKS, AT, ATS, user_id, tweet_id, count, range)
44
+ 16
45
+ 17
46
+
47
+ <ipython-input-77-a76659ff5e8f> in search_tweets(CK, CKS, AT, ATS, user_id, tweet_id, count, range)
48
+ 36 'UserID',
49
+ 37 'UserScreenName',
50
+ ---> 38 'PostMessage'])
51
+ 39
52
+ 40 df.to_csv('jr1.csv', encoding="utf-8") # CSV形式で保存
53
+
54
+ ~/opt/anaconda3/lib/python3.7/site-packages/pandas/core/frame.py in __init__(self, data, index, columns, dtype, copy)
55
+ 521 mgr = arrays_to_mgr(arrays, columns, index, columns, dtype=dtype)
56
+ 522 else:
57
+ --> 523 mgr = init_ndarray(data, index, columns, dtype=dtype, copy=copy)
58
+ 524 else:
59
+ 525 mgr = init_dict({}, index, columns, dtype=dtype)
60
+
61
+ ~/opt/anaconda3/lib/python3.7/site-packages/pandas/core/internals/construction.py in init_ndarray(values, index, columns, dtype, copy)
62
+ 232 block_values = [values]
63
+ 233
64
+ --> 234 return create_block_manager_from_blocks(block_values, [columns, index])
65
+ 235
66
+ 236
67
+
68
+ ~/opt/anaconda3/lib/python3.7/site-packages/pandas/core/internals/managers.py in create_block_manager_from_blocks(blocks, axes)
69
+ 1670 blocks = [getattr(b, "values", b) for b in blocks]
70
+ 1671 tot_items = sum(b.shape[0] for b in blocks)
71
+ -> 1672 raise construction_error(tot_items, blocks[0].shape[1:], axes, e)
72
+ 1673
73
+ 1674
74
+
10
75
  ValueError: Shape of passed values is (6, 1), indices imply (6, 6)
76
+
11
77
  ```
12
78
  csvも保存されておらずかつDataFrameも表示されません。
13
79
 

1

エラー文の修正

2020/09/14 07:28

投稿

naochan1027
naochan1027

スコア2

title CHANGED
File without changes
body CHANGED
@@ -7,7 +7,7 @@
7
7
  ### 発生している問題・エラーメッセージ
8
8
 
9
9
  ```
10
- Shape of passed values is (6, 1), indices imply (6, 6)
10
+ ValueError: Shape of passed values is (6, 1), indices imply (6, 6)
11
11
  ```
12
12
  csvも保存されておらずかつDataFrameも表示されません。
13
13