2016-05-16 93 views
1

好的,所以我在嘗試讓我的代碼工作時遇到問題,我的目標是讓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' –

回答

1

當通過字符串訪問列表時,引發這種類型的錯誤,優先於允許通過字符串索引的字典。

如果可能的話出現此錯誤的註釋行,或者您可以檢查打印類型的數據類型並檢查它是否真的是字典。但是確保JSON的結構像字典一樣,或者裏面有列表。

相關問題