如何将推文实时发送到外部资源?

2024-04-29 19:18:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚开始编程,没有人可以信赖它。我真的不知道发生了什么以及如何修复它

我想使用Twitter的API检索实时推文的文本数据,并将其存储在名为test.txt的文件和redis服务器中

错误

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'

代码

import os
import tweepy
import redis
import math
from collections import Counter

r = redis.Redis(host='localhost', port=6379, db=0)

TWITTER_CLIENT_ID = os.environ['TWITTER_CLIENT_ID']
TWITTER_CLIENT_SECRET = os.environ['TWITTER_CLIENT_SECRET']

TWITTER_OAUTH_TOKEN = os.environ['TWITTER_OAUTH_TOKEN']
TWITTER_OAUTH_TOKEN_SECRET = os.environ['TWITTER_OAUTH_TOKEN_SECRET']

auth = tweepy.OAuthHandler(TWITTER_CLIENT_ID,TWITTER_CLIENT_SECRET)
auth.set_access_token(TWITTER_OAUTH_TOKEN,TWITTER_OAUTH_TOKEN_SECRET)

class StreamListener(tweepy.StreamListener):
    def on_status(self, status):
        status = []
        file = open('test.txt', 'w')
        if status.lang == 'ja':
            file.write(status)
            file.close()

    def on_error(self, status_code):
        return False

stream = tweepy.Stream(auth=auth, listener=StreamListener())
stream.sample()

附加信息

iOS 10.12.6、Python 3.7.3、Atom


Tags: inpylibstatuslinesitetwitterdirenv