gpt4 book ai didi

python - JSON 格式的 "TypeError: list indices must be integers, not str"

转载 作者:太空宇宙 更新时间:2023-11-03 16:35:32 25 4
gpt4 key购买 nike

好吧,我在尝试让我的代码正常工作时遇到了麻烦,我的目标是创建一个 Reddit 机器人,它引用 Steam 的 appid JSON,以便在用户说出游戏名称时将用户链接到 Steam 商店页面。

机器人几乎完成了,但是,当机器人运行时,我不断收到“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的初学者,所以放轻松。

最佳答案

当通过字符串访问列表时,会引发此类错误,尤其是允许通过字符串索引的字典。

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

关于python - JSON 格式的 "TypeError: list indices must be integers, not str",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37245782/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com