Twitter APIを用いてリアルタイムで取得した日本語のツイートをtest.txtというファイルを新規に作成してそこに書き込まれるようにしたいと思っているのですが、以下の箇所に自信がありません。
status = [] file = open('test.txt', 'w') if status.lang == 'ja': file.write(status) file.close()
更に、実行しようとしたところ以下のエラーが出ました。
同時に複数の質問をしてしまい恐縮ですが、どのようにコードを改良したら解決するのか、教えていただけますと幸いです。
Traceback (most recent call last): File "tweet_get.py", line 30, in <module> stream.sample() File "/Users/macuser/Workspaces/jxpress/trendword/.direnv/python-3.7.3/lib/python3.7/site-packages/tweepy/streaming.py", line 449, in sample self._start(is_async) File "/Users/macuser/Workspaces/jxpress/trendword/.direnv/python-3.7.3/lib/python3.7/site-packages/tweepy/streaming.py", line 389, in _start self._run() File "/Users/macuser/Workspaces/jxpress/trendword/.direnv/python-3.7.3/lib/python3.7/site-packages/tweepy/streaming.py", line 320, in _run six.reraise(*exc_info) File "/Users/macuser/Workspaces/jxpress/trendword/.direnv/python-3.7.3/lib/python3.7/site-packages/six.py", line 693, in reraise raise value File "/Users/macuser/Workspaces/jxpress/trendword/.direnv/python-3.7.3/lib/python3.7/site-packages/tweepy/streaming.py", line 289, in _run self._read_loop(resp) File "/Users/macuser/Workspaces/jxpress/trendword/.direnv/python-3.7.3/lib/python3.7/site-packages/tweepy/streaming.py", line 351, in _read_loop self._data(next_status_obj) File "/Users/macuser/Workspaces/jxpress/trendword/.direnv/python-3.7.3/lib/python3.7/site-packages/tweepy/streaming.py", line 323, in _data if self.listener.on_data(data) is False: File "/Users/macuser/Workspaces/jxpress/trendword/.direnv/python-3.7.3/lib/python3.7/site-packages/tweepy/streaming.py", line 54, in on_data if self.on_status(status) is False: File "tweet_get.py", line 22, in on_status if status.lang == 'ja': AttributeError: 'list' object has no attribute 'lang'
python
1import os 2import tweepy 3import math 4from collections import Counter 5 6TWITTER_CLIENT_ID = os.environ['TWITTER_CLIENT_ID'] 7TWITTER_CLIENT_SECRET = os.environ['TWITTER_CLIENT_SECRET'] 8 9TWITTER_OAUTH_TOKEN = os.environ['TWITTER_OAUTH_TOKEN'] 10TWITTER_OAUTH_TOKEN_SECRET = os.environ['TWITTER_OAUTH_TOKEN_SECRET'] 11 12auth = tweepy.OAuthHandler(TWITTER_CLIENT_ID,TWITTER_CLIENT_SECRET) 13auth.set_access_token(TWITTER_OAUTH_TOKEN,TWITTER_OAUTH_TOKEN_SECRET) 14 15class StreamListener(tweepy.StreamListener): 16 def on_status(self, status): 17 status = [] 18 file = open('test.txt', 'w') 19 if status.lang == 'ja': 20 file.write(status) 21 file.close() 22 23 def on_error(self, status_code): 24 return False 25 26stream = tweepy.Stream(auth=auth, listener=StreamListener()) 27stream.sample()
補足情報(FW/ツールのバージョンなど)
iOS 10.12.6, Python 3.7.3, Atom
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/08/16 01:38
2019/08/16 03:53 編集
2019/08/16 04:25