【问题标题】:Parsing Status JSON from Twitter using Python to find statuses count使用 Python 从 Twitter 解析状态 JSON 以查找状态计数
【发布时间】:2015-01-31 15:40:01
【问题描述】:

我正在使用 Tweepy 获取 @UserName 发布的所有推文。这是下面的代码

import urllib, json
import sys
import tweepy
from tweepy import OAuthHandler

def twitter_fetch(screen_name = "prateek",maxnumtweets=10):

consumer_token = "" #Keys removed for security
consumer_secret = ""
access_token = ""
access_secret = ""

auth = tweepy.OAuthHandler(consumer_token,consumer_secret)
auth.set_access_token(access_token,access_secret)

api  = tweepy.API(auth)

for status in tweepy.Cursor(api.user_timeline,id=screen_name).items(1):
    print status['statuses_count']
    print '\n'



if __name__ == '__main__':
twitter_fetch('BarackObama',200)

如何正确解析 JSON 以读取该特定用户的状态数?

【问题讨论】:

  • 如果您将查询的 JSON 输出发布到 pastebin 上会很有帮助?
  • @SamCyanide pastebin.com/C1RiGUtF - 绝对不变的输出
  • 所以你想计算一个特定人的推文总数吗?这就是你要找的全部吗?无需迭代某些东西,就像编写简单的代码行一样简单,tweepy 将为您完成所有工作。告诉我你是否也在寻找同样的东西

标签: python json twitter tweepy


【解决方案1】:

记录您已迭代多少个状态的东西怎么样?我不肯定 tweepy 的工作原理,但使用类似这样的东西:

statuses = 0
for status in tweepy.Cursor(api.user_timeline,id=screen_name).items(1):
    print status['statuses_count']
    statuses += 1
    print '\n'
return statuses

通常 JSON 数据具有良好的结构,格式清晰,如下所示,更易于理解。

因此,当我想遍历此列表以查找是否存在 x 时(在本例中为成就),我使用此函数,它为每次迭代的索引添加 1。

def achnamefdr(appid,mykey,steamid64,achname):
    playerachurl = 'http://api.steampowered.com/ISteamUserStats/GetPlayerAchievements/v0001/?appid=' + str(appid) + '&key=' + mykey + '&steamid=' + steamid64 + '&l=name'

    achjson = json.loads(urllib.request.urlopen(playerachurl).read().decode('utf-8'))

    achjsonr = achjson['playerstats']['achievements']

    index = 0
    for ach in achjsonr:
        if not ach['name'].lower() == achname.lower():
            index += 1
            continue
        else:
            achnamef = ach['name']
            return achnamef, index, True
    return 'Invalid Achievement!', index, False

【讨论】:

  • for status in tweepy.Cursor(api.user_timeline,id=screen_name).items(1) 此行将循环迭代的次数与作为 items() 的参数给出的数字一样多。我想 - 也许我们只是阅读了一条 JSON 格式的推文/状态,我们得到了他一生中发布的推文数量。然后我们使用该数字遍历循环,将状态数作为参数提供给 items()
【解决方案2】:

可以通过从status._json获取JSON对象,然后解析..

print status._json["statuses_count"]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-28
    • 2018-06-26
    • 2012-10-14
    • 1970-01-01
    • 2015-03-31
    • 2013-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多