“类型错误:列表索引必须是整数,而不是str”in JSON

问题描述:

好的,所以我在尝试让我的代码工作时遇到问题,我的目标是让Reddit Bot引用Steam的appid JSON来将用户链接到当用户说出游戏名称时的蒸汽存储页面。“类型错误:列表索引必须是整数,而不是str”in JSON

机器人几乎完成,但是,当机器人运行时,我总是收到“TypeError:列表索引必须是整数,而不是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

你可以添加哪行代码抛出错误?由于错误提示您可能试图将其索引到列表中,但是您正在使用“str”类型变量而不是“int”。我怀疑它是'comment.reply(''applist'] ['apps'] ['app'] ['appid'])这行 - 这看起来不像是有效的Python,我认为你是丢失'dic'变量 –

+0

@TomSitter'['applist'] ['apps']'**是**有效的python语法...但是它总是会引起OP运行时出现的确切错误,我强烈建议你张贴作为答案,因为它很可能是正确的解决方案。 –

+0

@TomSitter '文件 “C:\用户\肖恩史蒂文斯\桌面\书签交易机器人\蒸汽博特\ obot.py!”,第42行,在 words_to_reply = DIC [ 'APPLIST'] ['应用 '] ['app'] ['name'] TypeError:列表索引必须是整数,而不是str' –

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

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