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

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

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

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

Q&A

1回答

2779閲覧

ポジティブ、ネガティブなツイートを取得、整形したい。

giro1975

総合スコア37

Python

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

0グッド

1クリップ

投稿2018/10/07 09:13

編集2022/01/12 10:55

環境
Windows10
Python 3.6.5 |Anaconda, Inc.|

形態素解析を勉強しています。Aidemy様のこのブログを実践したいです。
https://blog.aidemy.net/entry/2018/09/26/102646

このブログのコードを変更して実行したいです。

しかし
ポジティブ、ネガティブなツイートを取得、そして整形するところでエラーが出て、修正できません。

長くて申し訳ございません。エラーへの対処法を教えてください。

#ポジティブ、ネガティブなツイートを取得、そして整形 ※ここでエラー pos_tweets = get_positive_tweets() neg_tweets = get_negative_tweets() tokenized_pos_tweets = tokenize(pos_tweets) tokenized_neg_tweets = tokenize(neg_tweets)
TweepError: Failed to send request: HTTPSConnectionPool(host='api.twitter.com', port=443): Max retries exceeded with url: /1.1/statuses/user_timeline.json?id=positive_bot_00&count=200 (Caused by SSLError(SSLError("bad handshake: SysCallError(10054, 'WSAECONNRESET')",),))

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

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

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

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

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

wwbQzhMkhhgEmhU

2018/10/07 09:41

整形してるところではなく、初回のtwitterのAPI呼び出しで失敗して切断されてるように見えます。
YasuhiroNiji

2018/10/07 13:14

他人のブログからこれだけコードをコピーすると著作権の問題がでるかもしれません。質問に必要な部分のみに限定する方が見やすいしベターだと思います。エラーメッセージの上にどの場所でエラーが発生したかの情報があるはずです。その情報を質問に追加できないでしょうか。
giro1975

2018/10/08 08:56

ありがとうございます。まず著作権の問題などでないように、大幅にコードを削除しました。
giro1975

2018/10/08 09:10

TweepErrorTraceback (most recent call last) <ipython-input-58-bbf35820c8c1> in <module>() ----> 1 pos_tweets = get_positive_tweets() 2 neg_tweets = get_negative_tweets() 3 4 tokenized_pos_tweets = tokenize(pos_tweets) 5 tokenized_neg_tweets = tokenize(neg_tweets) <ipython-input-55-eb1dcb46b60b> in get_positive_tweets() 15 16 for pos_id in positive_ids: ---> 17 tmp,max_id = get_tweet(pos_id,200) 18 tmp = list(set(tmp)) 19 for i in range(len(tmp)): <ipython-input-52-5ff1ac870175> in get_tweet(user_id, count) 7 def get_tweet(user_id,count): 8 API = get_twitter_api(CK, CS, AK, AT) ----> 9 data = API.user_timeline(id=user_id, count=count) 10 tweets = [] 11 for tweet in data: /usr/local/lib/python2.7/dist-packages/tweepy/binder.pyc in _call(*args, **kwargs) 248 return method 249 else: --> 250 return method.execute() 251 252 # Set pagination mode /usr/local/lib/python2.7/dist-packages/tweepy/binder.pyc in execute(self) 190 proxies=self.api.proxy) 191 except Exception as e: --> 192 six.reraise(TweepError, TweepError('Failed to send request: %s' % e), sys.exc_info()[2]) 193 194 rem_calls = resp.headers.get('x-rate-limit-remaining') /usr/local/lib/python2.7/dist-packages/tweepy/binder.pyc in execute(self) 188 timeout=self.api.timeout, 189 auth=auth, --> 190 proxies=self.api.proxy) 191 except Exception as e: 192 six.reraise(TweepError, TweepError('Failed to send request: %s' % e), sys.exc_info()[2]) /usr/local/lib/python2.7/dist-packages/requests/sessions.pyc in request(self, method, url, params, data, headers, cookies, files, auth, timeout, allow_redirects, proxies, hooks, stream, verify, cert, json) 492 hooks=hooks, 493 ) --> 494 prep = self.prepare_request(req) 495 496 proxies = proxies or {} /usr/local/lib/python2.7/dist-packages/requests/sessions.pyc in prepare_request(self, request) 435 auth=merge_setting(auth, self.auth), 436 cookies=merged_cookies, --> 437 hooks=merge_hooks(request.hooks, self.hooks), 438 ) 439 return p /usr/local/lib/python2.7/dist-packages/requests/models.pyc in prepare(self, method, url, headers, files, data, params, auth, cookies, hooks, json) 307 self.prepare_cookies(cookies) 308 self.prepare_body(data, files, json) --> 309 self.prepare_auth(auth, url) 310 311 # Note that prepare_auth must be last to enable authentication schemes /usr/local/lib/python2.7/dist-packages/requests/models.pyc in prepare_auth(self, auth, url) 538 539 # Allow auth to make its changes. --> 540 r = auth(self) 541 542 # Update self to reflect the auth changes. /usr/local/lib/python2.7/dist-packages/requests_oauthlib/oauth1_auth.pyc in __call__(self, r) 86 # Omit body data in the signing of non form-encoded requests 87 r.url, headers, _ = self.client.sign( ---> 88 unicode(r.url), unicode(r.method), None, r.headers) 89 90 r.prepare_headers(headers) /usr/local/lib/python2.7/dist-packages/oauthlib/oauth1/rfc5849/__init__.pyc in sign(self, uri, http_method, body, headers, realm) 312 # generate the signature 313 request.oauth_params.append( --> 314 ('oauth_signature', self.get_oauth_signature(request))) 315 316 # render the signed request and return it /usr/local/lib/python2.7/dist-packages/oauthlib/oauth1/rfc5849/__init__.pyc in get_oauth_signature(self, request) 127 self.resource_owner_secret) 128 --> 129 uri, headers, body = self._render(request) 130 131 collected_params = signature.collect_parameters( /usr/local/lib/python2.7/dist-packages/oauthlib/oauth1/rfc5849/__init__.pyc in _render(self, request, formencode, realm) 209 if self.signature_type == SIGNATURE_TYPE_AUTH_HEADER: 210 headers = parameters.prepare_headers( --> 211 request.oauth_params, request.headers, realm=realm) 212 elif self.signature_type == SIGNATURE_TYPE_BODY and request.decoded_body is not None: 213 body = parameters.prepare_form_encoded_body( /usr/local/lib/python2.7/dist-packages/oauthlib/oauth1/rfc5849/utils.pyc in wrapper(params, *args, **kwargs) 30 def wrapper(params, *args, **kwargs): 31 params = filter_oauth_params(params) ---> 32 return target(params, *args, **kwargs) 33 34 wrapper.__doc__ = target.__doc__ /usr/local/lib/python2.7/dist-packages/oauthlib/oauth1/rfc5849/parameters.pyc in prepare_headers(oauth_params, headers, realm) 57 # .. _`Section 3.6`: https://tools.ietf.org/html/rfc5849#section-3.6 58 escaped_name = utils.escape(oauth_parameter_name) ---> 59 escaped_value = utils.escape(value) 60 61 # 2. Each parameter's name is immediately followed by an "=" character /usr/local/lib/python2.7/dist-packages/oauthlib/oauth1/rfc5849/utils.pyc in escape(u) 55 if not isinstance(u, unicode_type): 56 raise ValueError('Only unicode objects are escapable. ' + ---> 57 'Got %r of type %s.' % (u, type(u))) 58 # Letters, digits, and the characters '_.-' are already treated as safe 59 # by urllib.quote(). We need to add '~' to fully support rfc5849. TweepError: Failed to send request: Only unicode objects are escapable. Got <generator object <genexpr> at 0x7f335cbc2e60> of type <type 'generator'>.
giro1975

2018/10/08 09:11

Google Colabotaroryで試しました。上記のエラーでした。もしなにかお分かりになれば教えてください。よろしくお願いいたします。
YasuhiroNiji

2018/10/08 09:51

Google Colabotarory で、Python2のノートブックを使っているので、Python3のノートブックを使って試してください。
giro1975

2018/10/08 14:34

ありがとございます。試しました。--------------------------------------------------------------------------- ValueError Traceback (most recent call last) /usr/local/lib/python3.6/dist-packages/tweepy/binder.py in execute(self) 189 auth=auth, --> 190 proxies=self.api.proxy) 191 except Exception as e: /usr/local/lib/python3.6/dist-packages/requests/sessions.py in request(self, method, url, params, data, headers, cookies, files, auth, timeout, allow_redirects, proxies, hooks, stream, verify, cert, json) 493 ) --> 494 prep = self.prepare_request(req) 495 /usr/local/lib/python3.6/dist-packages/requests/sessions.py in prepare_request(self, request) 436 cookies=merged_cookies, --> 437 hooks=merge_hooks(request.hooks, self.hooks), 438 ) /usr/local/lib/python3.6/dist-packages/requests/models.py in prepare(self, method, url, headers, files, data, params, auth, cookies, hooks, json) 308 self.prepare_body(data, files, json) --> 309 self.prepare_auth(auth, url) 310 /usr/local/lib/python3.6/dist-packages/requests/models.py in prepare_auth(self, auth, url) 539 # Allow auth to make its changes. --> 540 r = auth(self) 541 /usr/local/lib/python3.6/dist-packages/requests_oauthlib/oauth1_auth.py in __call__(self, r) 87 r.url, headers, _ = self.client.sign( ---> 88 unicode(r.url), unicode(r.method), None, r.headers) 89 /usr/local/lib/python3.6/dist-packages/oauthlib/oauth1/rfc5849/__init__.py in sign(self, uri, http_method, body, headers, realm) 313 request.oauth_params.append( --> 314 ('oauth_signature', self.get_oauth_signature(request))) 315 /usr/local/lib/python3.6/dist-packages/oauthlib/oauth1/rfc5849/__init__.py in get_oauth_signature(self, request) 128 --> 129 uri, headers, body = self._render(request) 130 /usr/local/lib/python3.6/dist-packages/oauthlib/oauth1/rfc5849/__init__.py in _render(self, request, formencode, realm) 210 headers = parameters.prepare_headers( --> 211 request.oauth_params, request.headers, realm=realm) 212 elif self.signature_type == SIGNATURE_TYPE_BODY and request.decoded_body is not None: /usr/local/lib/python3.6/dist-packages/oauthlib/oauth1/rfc5849/utils.py in wrapper(params, *args, **kwargs) 31 params = filter_oauth_params(params) ---> 32 return target(params, *args, **kwargs) 33 /usr/local/lib/python3.6/dist-packages/oauthlib/oauth1/rfc5849/parameters.py in prepare_headers(oauth_params, headers, realm) 58 escaped_name = utils.escape(oauth_parameter_name) ---> 59 escaped_value = utils.escape(value) 60 /usr/local/lib/python3.6/dist-packages/oauthlib/oauth1/rfc5849/utils.py in escape(u) 56 raise ValueError('Only unicode objects are escapable. ' + ---> 57 'Got %r of type %s.' % (u, type(u))) 58 # Letters, digits, and the characters '_.-' are already treated as safe ValueError: Only unicode objects are escapable. Got <generator object to_unicode.<locals>.<genexpr> at 0x7f74e606fc50> of type <class 'generator'>. During handling of the above exception, another exception occurred: TweepError Traceback (most recent call last) <ipython-input-8-bbf35820c8c1> in <module>() ----> 1 pos_tweets = get_positive_tweets() 2 neg_tweets = get_negative_tweets() 3 4 tokenized_pos_tweets = tokenize(pos_tweets) 5 tokenized_neg_tweets = tokenize(neg_tweets) <ipython-input-5-eb1dcb46b60b> in get_positive_tweets() 15 16 for pos_id in positive_ids: ---> 17 tmp,max_id = get_tweet(pos_id,200) 18 tmp = list(set(tmp)) 19 for i in range(len(tmp)): <ipython-input-4-5ff1ac870175> in get_tweet(user_id, count) 7 def get_tweet(user_id,count): 8 API = get_twitter_api(CK, CS, AK, AT) ----> 9 data = API.user_timeline(id=user_id, count=count) 10 tweets = [] 11 for tweet in data: /usr/local/lib/python3.6/dist-packages/tweepy/binder.py in _call(*args, **kwargs) 248 return method 249 else: --> 250 return method.execute() 251 252 # Set pagination mode /usr/local/lib/python3.6/dist-packages/tweepy/binder.py in execute(self) 190 proxies=self.api.proxy) 191 except Exception as e: --> 192 six.reraise(TweepError, TweepError('Failed to send request: %s' % e), sys.exc_info()[2]) 193 194 rem_calls = resp.headers.get('x-rate-limit-remaining') /usr/local/lib/python3.6/dist-packages/six.py in reraise(tp, value, tb) 690 value = tp() 691 if value.__traceback__ is not tb: --> 692 raise value.with_traceback(tb) 693 raise value 694 finally: /usr/local/lib/python3.6/dist-packages/tweepy/binder.py in execute(self) 188 timeout=self.api.timeout, 189 auth=auth, --> 190 proxies=self.api.proxy) 191 except Exception as e: 192 six.reraise(TweepError, TweepError('Failed to send request: %s' % e), sys.exc_info()[2]) /usr/local/lib/python3.6/dist-packages/requests/sessions.py in request(self, method, url, params, data, headers, cookies, files, auth, timeout, allow_redirects, proxies, hooks, stream, verify, cert, json) 492 hooks=hooks, 493 ) --> 494 prep = self.prepare_request(req) 495 496 proxies = proxies or {} /usr/local/lib/python3.6/dist-packages/requests/sessions.py in prepare_request(self, request) 435 auth=merge_setting(auth, self.auth), 436 cookies=merged_cookies, --> 437 hooks=merge_hooks(request.hooks, self.hooks), 438 ) 439 return p /usr/local/lib/python3.6/dist-packages/requests/models.py in prepare(self, method, url, headers, files, data, params, auth, cookies, hooks, json) 307 self.prepare_cookies(cookies) 308 self.prepare_body(data, files, json) --> 309 self.prepare_auth(auth, url) 310 311 # Note that prepare_auth must be last to enable authentication schemes /usr/local/lib/python3.6/dist-packages/requests/models.py in prepare_auth(self, auth, url) 538 539 # Allow auth to make its changes. --> 540 r = auth(self) 541 542 # Update self to reflect the auth changes. /usr/local/lib/python3.6/dist-packages/requests_oauthlib/oauth1_auth.py in __call__(self, r) 86 # Omit body data in the signing of non form-encoded requests 87 r.url, headers, _ = self.client.sign( ---> 88 unicode(r.url), unicode(r.method), None, r.headers) 89 90 r.prepare_headers(headers) /usr/local/lib/python3.6/dist-packages/oauthlib/oauth1/rfc5849/__init__.py in sign(self, uri, http_method, body, headers, realm) 312 # generate the signature 313 request.oauth_params.append( --> 314 ('oauth_signature', self.get_oauth_signature(request))) 315 316 # render the signed request and return it /usr/local/lib/python3.6/dist-packages/oauthlib/oauth1/rfc5849/__init__.py in get_oauth_signature(self, request) 127 self.resource_owner_secret) 128 --> 129 uri, headers, body = self._render(request) 130 131 collected_params = signature.collect_parameters( /usr/local/lib/python3.6/dist-packages/oauthlib/oauth1/rfc5849/__init__.py in _render(self, request, formencode, realm) 209 if self.signature_type == SIGNATURE_TYPE_AUTH_HEADER: 210 headers = parameters.prepare_headers( --> 211 request.oauth_params, request.headers, realm=realm) 212 elif self.signature_type == SIGNATURE_TYPE_BODY and request.decoded_body is not None: 213 body = parameters.prepare_form_encoded_body( /usr/local/lib/python3.6/dist-packages/oauthlib/oauth1/rfc5849/utils.py in wrapper(params, *args, **kwargs) 30 def wrapper(params, *args, **kwargs): 31 params = filter_oauth_params(params) ---> 32 return target(params, *args, **kwargs) 33 34 wrapper.__doc__ = target.__doc__ /usr/local/lib/python3.6/dist-packages/oauthlib/oauth1/rfc5849/parameters.py in prepare_headers(oauth_params, headers, realm) 57 # .. _`Section 3.6`: https://tools.ietf.org/html/rfc5849#section-3.6 58 escaped_name = utils.escape(oauth_parameter_name) ---> 59 escaped_value = utils.escape(value) 60 61 # 2. Each parameter's name is immediately followed by an "=" character /usr/local/lib/python3.6/dist-packages/oauthlib/oauth1/rfc5849/utils.py in escape(u) 55 if not isinstance(u, unicode_type): 56 raise ValueError('Only unicode objects are escapable. ' + ---> 57 'Got %r of type %s.' % (u, type(u))) 58 # Letters, digits, and the characters '_.-' are already treated as safe 59 # by urllib.quote(). We need to add '~' to fully support rfc5849. TweepError: Failed to send request: Only unicode objects are escapable. Got <generator object to_unicode.<locals>.<genexpr> at 0x7f74e606fc50> of type <class 'generator'>.
YasuhiroNiji

2018/10/09 00:49

回答の方に詳細はかいておきました。次回質問をするときは、エラーはコードだけでなく、Tracebackの部分を入れておくと原因がわかりやすいです。
guest

回答1

0

エラーは最初のAPIの部分で発生しています。以下のようにしてget_twitter_apiから順番にそのコードが動作するかどうかチェックしていったらいいと思います。

python

1def get_twitter_api(CK, CS, AK, AT): 2 auth = tweepy.OAuthHandler(CK, CS) 3 auth.set_access_token(AK, AT) 4 api = tweepy.API(auth) 5 return api 6 7get_twitter_api(CK, CS, AK, AT)

ここでCK等は次のようなもので、その設定に問題があるように思われます。
CK: consumer_key
CS: consumer secret
AK: access key
AT: access token

Google ColabotaroryでのエラーとWindowsのエラーが異なります。Windowsの場合"bad handshake: SysCallError(10054, 'WSAECONNRESET')"ということでなので、twitterとのhttpsの接続ができていません。Windowsを会社や学校で使っている場合、プロキシーサーバー経由で接続する必要があります。その設定を確認してみてください。

投稿2018/10/07 13:08

編集2018/10/09 00:47
YasuhiroNiji

総合スコア584

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

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

giro1975

2018/10/09 14:36

ありがとうございます。 上から順に区切って実行するとやはり問題の箇所でエラーが生じます。 def get_twitter_api(CK, CS, AK, AT): auth = tweepy.OAuthHandler(CK, CS) auth.set_access_token(AK, AT) api = tweepy.API(auth) return api get_twitter_api(CK, CS, AK, AT) を実行すると <tweepy.api.API at 0x7fea2d604400> と表示されます。
giro1975

2018/10/09 14:37

問題のところのエラーコードは TweepError: Failed to send request: Only unicode objects are escapable. Got <generator object to_unicode.<locals>.<genexpr> at 0x7fea2d5a5a40> of type <class 'generator'>. となっています。
YasuhiroNiji

2018/10/09 22:00

その内容だけだと判断できないのでCK, CS, AK, ATをどのように設定したかを書いて、新しい質問にしたらいいと思います。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだベストアンサーが選ばれていません

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

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

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

ただいまの回答率
85.50%

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

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

質問する

関連した質問