【问题标题】:Downloading Full JSON data from Tweets Using Rest API and Tweepy, Querying by Tweet ID使用 Rest API 和 Tweepy 从 Tweets 下载完整的 JSON 数据,通过 Tweet ID 查询
【发布时间】:2014-03-26 15:50:16
【问题描述】:

对于使用 tweepy 和 Twitter 的 API 来说是全新的,我意识到(为时已晚)我在收集一些 Twitter 数据时犯了许多错误。我一直在收集有关冬季奥运会的推文,并一直在使用 Streaming API 按搜索词进行过滤。但是,我只检索了文本、日期时间和推文 ID,而不是检索所有可用数据。下面是一个实现的流监听器示例:

import os
import sys
import tweepy

os.chdir('/my/preferred/location/Twitter Olympics/Data')

consumer_key = 'cons_key'
consumer_secret = 'cons_sec'
access_token = 'access_token'
access_secret = 'access_sec'

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
api = tweepy.API(auth)

# count is used to give an approximation of how many tweets I'm pulling at a given time.

count = []
f = open('feb24.txt', 'a')

class StreamListener(tweepy.StreamListener):
    def on_status(self, status):
        print 'Running...'
        info = status.text, status.created_at, status.id
        f.write(str(info))
        for i in info:
          count.append(1)

    def on_error(self, status_code):
        print >> sys.stderr, "Encountered error with status code: ", status_code

    def on_timeout(self):
        print >> sys.stderr, "Timeout..."
        return True

sapi = tweepy.streaming.Stream(auth, StreamListener())
sapi.filter(track=["olympics", "olympics 2014", "sochi", "Sochi2014", "sochi 2014",      "2014Sochi", "winter olympics"])

.txt 文件中存储的输出示例如下: ('RT @Visa: There can only be one winner. Soak it in #TeamUSA, this is your #everywhere #Sochi2014 @987654321@', datetime.datetime(2014, 2, 15, 18, 9, 51), 111111111111111111).

所以,这是我的问题。如果我能够在列表中获取 Tweet ID,有没有办法遍历这些以查询 Twitter Rest API 并检索完整的 JSON 文件?我的预感是肯定的,但我不确定实现,主要是关于如何将结果数据保存为 JSON 文件(因为我在这里一直使用 .txt 文件)。提前感谢您的阅读。

【问题讨论】:

    标签: python json rest twitter tweepy


    【解决方案1】:

    想通了。对于犯了这个可怕错误的人(只需获取所有数据开始!)这里有一些带有正则表达式的代码,它将提取 ID 号并将它们存储为一个列表:

    import re
    
    # Read in your ugly text file.
    tweet_string = open('nameoffile.txt', 'rU')
    tweet_string = tweet_string.read()
    
    # Find all the id numbers with a regex.
    id_finder = re.compile('[0-9]{18,18}')
    
    # Go through the twee_string object and find all 
    # the IDs that meet the regex criteria.
    idList = re.findall(id_finder, tweet_string)
    

    现在您可以遍历列表 idList 并将每个 ID 作为查询提供给 api(假设您已完成身份验证并拥有 api 类的实例)。然后,您可以将这些附加到列表中。比如:

    tweet_list = []
    for id in idList:
        tweet = api.get_status(id)
        tweet_list.append(tweet)
    

    重要提示:tweet_list 变量中将附加一个 tweepy status object。我需要解决这个问题,但是上面的问题已经解决了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-17
      • 1970-01-01
      • 2020-01-21
      • 2014-06-19
      相关资源
      最近更新 更多