如何 json 将 tweepy 流转储到文本文件中?

How to json dump tweepy stream into text file?

您好,我看过许多关于如何执行此操作的指南和教程,但我无法使用 tweepy 将 JSON 数据存储在文本文件中。

class StreamListener(tweepy.StreamListener): 

def on_status(self, status):

    print(status)

def on_error(self, status):

    print status
    if status == 420:

        return False



if __name__ == '__main__':

stream_listener = StreamListener()
auth = tweepy.OAuthHandler(consumer_token, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
stream = tweepy.Stream(auth, stream_listener)

我有另一个 python 文件,它应该将数据读入列表:

import pandas
import json

json_data = 'twitter_data.txt'

data_list = []
#load file 
tweets_file = open(json_data, "r")
for line in tweets_file:
try:
    tweet = json.loads(line) #this line causes problems
    data_list.append(tweet)
except:
    continue


print len(data_list)

我认为从 Twitter 收到的数据是 JSON 格式的,我遵循的指南都说是,但实际上它在另一个对象中。

我是否应该将所有内容都存储在一个列表中,然后 json 将该列表转储到新的文本文件中?

看来您的方向是正确的。您可以修改流监听器以将推文直接写入文件。

编辑: 现在以 JSON 格式写出。

#Import the necessary methods from tweepy library
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
from tweepy import API

#Variables that contains the user credentials to access Twitter API
CONSUMER_KEY = #YOUR CONSUMER KEY
CONSUMER_SECRET = #YOUR CONSUMER SECRET
ACCESS_TOKEN = #YOUR ACCESS TOKEN
ACCESS_TOKEN_SECRET = #YOUR ACCESS TOKEN SECRET

class FileWriteListener(StreamListener):

    def __init__(self):
        super(StreamListener, self).__init__()
        self.save_file = open('tweets.json','w')
        self.tweets = []

    def on_data(self, tweet):
        self.tweets.append(json.loads(tweet))
        self.save_file.write(str(tweet))

    def on_error(self, status):
        print(status)
        return True


auth = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)

api = API(auth)

twitter_stream = Stream(auth, MyListener())
# Here you can filter the stream by:
#    - keywords (as shown)
#    - users
twitter_stream.filter(track=['hello'])

此代码将 运行 无限期地执行,因此您需要在一段时间后退出进程 (Ctrl-C) 或修改代码。

然后就可以加载数据了:

import json

json_data = []
with open('tweets.json','r') as f:
    json_data.append( json.loads(f.readline()) )

希望对您有所帮助!

我想这可能是您要找的东西。

def on_status(self, tweet):
    json_dumps = json.dumps(tweet._json)
    tweet_json = json.loads(json_dumps)
    print(tweet_json['created_at'])

这些是您可以在 tweet_json[ ]

中使用的所有键

dict_keys(['created_at', 'id', 'id_str', 'text', 'source', 'truncated', 'in_reply_to_status_id', 'in_reply_to_status_id_str', 'in_reply_to_user_id', 'in_reply_to_user_id_str', 'in_reply_to_screen_name', 'user', 'geo', 'coordinates', 'place', 'contributors', 'retweeted_status', 'is_quote_status', 'quote_count', 'reply_count', 'retweet_count', 'favorite_count', 'entities', 'favorited', 'retweeted', 'filter_level', 'lang', 'timestamp_ms'])