" TypeError:list indices必须是整数,而不是str"在JSON中

时间:2016-05-16 02:14:36

标签: python json

好的,所以我在尝试让我的代码工作时遇到了麻烦,我的目标是制作一个引用Steam的appid JSON的Reddit Bot,当用户说出名字时将用户链接到Steam商店页面一场比赛。

机器人几乎完成了,但是,我一直得到" TypeError:list indices必须是整数,而不是str"当机器人运行时。

这是我的代码:

import praw
import time
import json
import codecs

# Death Zone /// I hope you have coffee, brcause you won't leave until this is done

with open('API.json', encoding='utf-8-sig') as steam_strings:
    dic = json.loads(steam_strings.read())
    print("Successfully read JSON")


a = dic.get('appid')
n = dic.get('name')

[app['name'] for app in dic['applist']['apps']['app']]


# End Death Zone


app_id = 'CENSORED'
app_secret = 'CENSORED'
app_uri = 'https://127.0.0.1:65010/authorize_callback'
app_ua = 'Stop asking me how to get the Windows flair dummy, I am here for that reason'
app_scopes = 'account creddits edit flair history identity livemanage modconfig modcontributors modflair modlog modothers modposts modself modwiki mysubreddits privatemessages read report save submit subscribe vote wikiedit wikiread'
app_account_code = 'CENSORED'
app_refresh = 'CENSORED'

import praw
def login():
    r = praw.Reddit(app_ua)
    r.set_oauth_app_info(app_id, app_secret, app_uri)
    r.refresh_access_information(app_refresh)
    print("Steam Link Bot! Version Alpha 0.1.2")
    return r

r = login()


words_to_reply = dic['applist']['apps']['app']['name']


# {'applist':1,'apps':2, 'app':3, 'name':4}

cache = []



def run_bot():
    subreddit = r.get_subreddit("eegras")
    comments = subreddit.get_comments(limit=100)
    for comment in comments:
        comment_text = comment.body.lower()
        isMatch = any(string in comment_text for string in words_to_reply)
        if comment.id not in cache and isMatch:
            comment.reply(['applist']['apps']['app']['appid'])
            cache.append(comment.id)
            print("I replied to a comment successfully!")



while True:
    run_bot()
    time.sleep(10)

任何帮助都会受到赞赏,我有点像Python的初学者,所以放轻松。

1 个答案:

答案 0 :(得分:1)

当通过字符串访问列表时,会引发这种类型的错误,该字符串是允许通过字符串索引的字典。

如果可能出现此错误的注释行,或者您可以检查创建打印类型的数据类型并检查它是否确实是字典。但是要确保JSON真的像字典一样构建,或者里面有列表。