【问题标题】:How to json dump tweepy stream into text file?如何将 tweepy 流 json 转储到文本文件中?
【发布时间】:2018-05-25 14:19:02
【问题描述】:

您好,我查看了许多关于如何执行此操作的指南和教程,但无法使用 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 将该列表转储到新的文本文件中?

【问题讨论】:

    标签: python json twitter tweepy


    【解决方案1】:

    看来您走在正确的轨道上。您可以修改流侦听器以将推文直接写入文件。

    编辑:现在以 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()) )
    

    希望这会有所帮助!

    【讨论】:

    • 感谢您的回复和帮助,但是这会让我在读取新文件时使用 json.loads 吗?我不相信它一开始就是 JSON 格式的,对吧?
    • 请注意,这包含整个json文件作为一个对象并将其存储在列表中,使列表长度只有1。但是列表中的每个条目都应该是一条推文。
    【解决方案2】:

    我认为这样的东西可能是您想要的。

    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', '截断', '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 ', '转推', 'filter_level', 'lang', 'timestamp_ms'])

    【讨论】:

      猜你喜欢
      • 2015-03-23
      • 2014-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-07
      • 2013-04-21
      • 2014-06-25
      • 1970-01-01
      相关资源
      最近更新 更多