python - 我的代码正在处理字典列表,就像字符串一样,类型错误: TypeError: string indices must be integers

标签 python json api reddit

所以我使用reddit api,由于某些与案例无关的原因,我想在这种情况下不使用reddit包装器来工作。代码实际上非常简单,它从 Reddit 子版 block 内的特定帖子中提取评论和 1 级回复。

这是函数的代码,

def getcommentsforpost(subredditname,postid,):

    #here we make the request to reddit, and create a python dictionary   
    #from the resulting json code


    reditpath = '/r/' + subredditname + '/comments/' + postid
    redditusual = 'https://www.reddit.com'
    parameters = '.json?'
    totalpath = redditusual + reditpath + parameters
    p = requests.get(totalpath, headers = {'User-agent' : 'Chrome'})
    result = p.json()

    #we are going to be looping a lot through dictionaries, to extract
    # the comments and their replies, thus, a list where we will insert  
    # them.
    totallist = [] 

    # the result object is a list with two dictionaries, one with info 
    #on the post, and the second one with all the info regarding the 
    #comments and their respective replies, because of this, we first 
    # process the posts info located in result[0]


    a = result[0]["data"]["children"][0]["data"]
    abody = a["selftext"]
    aauthor = a["author"]
    ascore = a["score"]
    adictionary = {"commentauthor" : aauthor , "comment" : abody , "Type" : "Post",
                       "commentscore" : ascore}

    totallist.append(adictionary)




    # and now, we start processing the comments, located in result[1]

    for i in result[1]["data"]["children"]:

        ibody = i["data"]["body"]
        iauthor = i["data"]["author"]
        iscore = i["data"]["score"]



        idictionary = {"commentauthor" : iauthor , "comment" : ibody , "Type" : "post_comment",
                       "commentscore" : iscore}

        totallist.append(idictionary)

       # to clarify, until here, the code works perfectly. No problem 
       # whatsoever, its exactly in the following section where  the 
       #error happens. 

       # we create a new object, called replylist, 
        #that contains a  list of dictionaries in every interaction of 
        #the loop. 

        replylists =  i["data"]["replies"]["data"]["children"]

        # we are going to loop through them, in every comment we extract


        for j in replylists:
            jauthor = j["data"]["author"]
            jbody = j["data"]["body"]
            jscore = j["data"]["score"]


            jdictionary = {"commentauthor" : jauthor , "comment" : jbody , "Type" : "comment_reply" , 
                           "commentscore" : jscore } 
            totallist.append(jdictionary)

        # just like we did with the post info and the normal comments,
         # we extract and put it in totallist. 



        finaldf = pd.DataFrame(totallist)



    return(finaldf)

getcommentsforpost("Python","a7zss0")

但是在对回复进行循环时,代码失败了。它返回此错误“字符串索引必须是整数”,向变量回复列表发出错误信号,但是,当我像这样在循环之外执行代码时

result[1]["data"]["children"][4]["data"]["replies"]["data"]["children"][0]

效果很好,应该是一样的效果。我相信它将回复列表视为字符串,而不是列表(这是它的类)

我尝试过的事情:

我尝试确保回复列表的类是一个带有 type() 函数的列表,它证明返回“list”,但只有 5 次循环交互,然后它会失败并出现相同的错误。

我尝试使用 for ja in range(0,len(replylists)) 进行列表循环,然后将 j 变量创建为 replylists[ja] 。它返回了相同的错误。

我已经调试了两个小时,没有该代码片段,该函数可以完美运行(当然,它不会在最终数据帧中返回回复,但它可以运行)。为什么会发生这种情况? replylists 是一个字典列表,而不是一个字符串,但它给出了奇怪的错误。

这是我们正在使用的函数的 reddit 文档: https://www.reddit.com/dev/api#GET_comments_ {文章}

要导入的库: 要求, Pandas 作为PD, json

我再说一遍,推荐包装器不是一个解决方案,我想用 json 和休息来解决这个问题。

正在研究这个: 'Python版本3.6.5 |Anaconda版本5.2.0,jupyter笔记本5.5.0'

提前谢谢您。希望它变得有趣,我会从这里继续工作。

最佳答案

我做了一些挖掘并将您的代码复制到本地环境并进行了一些调试,主要是:

try:
    replylists =  i["data"]["replies"]["data"]["children"]
except:
    for point in i['data']:
        print(point)
    exit()

通过这个,我发现事实上,i["data"] 有值(实际上有 57 个值),并且 57 个值之一包含回复,但是我查了一下,发现回复内容都是空的:

'replies': '' 是我直接打印出损坏值的 i 时看到的内容。

但是,我们并没有失去所有希望:您只是忘记忽略回复内容为空的迭代 (''),因为我还运行了检查以查看您的回复内容有多少迭代实际上失败了,有些成功,有些失败(由于前面提到的推理)。

有了这个,我建议您在出现这样的错误时使用 try except 进行调试(这是一项有用的技能),而且还有更多主题针对您的问题,弄清楚当回复内容为空时您想做什么。

祝您一切顺利,希望这对您有所帮助。

关于python - 我的代码正在处理字典列表,就像字符串一样,类型错误: TypeError: string indices must be integers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54297512/

相关文章:

python - CNTK 提示 LSTM 中的动态轴

python - C++ 代码中递减运算符后的等号

python - Seaborn 图 - X 轴上的错误日期

android - 将 JSON 输出解析为 ListView

ios - 由于 json 问题,Restkit 在 iOS 8 中崩溃?

api - 如何包含对 raml 资源的常见响应

rest - Openid 和 RestFul API

用于搜索专利数据库的 Python 模块,即 USPTO 或 EPO

ios - 如何使用 JSONModel 解析带有未知键的 json

angularjs - 与扩展程序外部的 Chrome 书签交互