Python 3.x &引用;索引器:无法匹配';int';“转换为索引大小的整数”;在字典里
我正在尝试用python创建一个discord机器人,并做一个xp模拟器,比如MEE6之类的。然而,当我尝试使用我目前拥有的东西时,我得到了一个错误。我目前的代码是:Python 3.x &引用;索引器:无法匹配';int';“转换为索引大小的整数”;在字典里,python-3.x,discord.py,index-error,Python 3.x,Discord.py,Index Error,我正在尝试用python创建一个discord机器人,并做一个xp模拟器,比如MEE6之类的。然而,当我尝试使用我目前拥有的东西时,我得到了一个错误。我目前的代码是: #A ton of imports def unload_cache(file: str): return open("cache/" + file, "r").read() def reload_cache(file: str, new): cache = open("cache/" + file, "w")
#A ton of imports
def unload_cache(file: str):
return open("cache/" + file, "r").read()
def reload_cache(file: str, new):
cache = open("cache/" + file, "w")
cache.write(str(new))
cache.close()
def add_xp(server_id, user_id, xp: int):
dicts = unload_cache("server_xp.txt")
try:
data = dicts[server_id]
try:
data[user_id] = data[user_id] + xp
dicts[server_id] = data
except KeyError:
data[user_id] = xp
dicts[server_id] = data
except:
dicts[server_id] = {user_id:xp}
reload_cache("server_xp.txt", dicts)
@bot.event
async def on_message(message):
server_id = int(message.server.id)
add_xp(server_id, message.author.id, 1)
print(message.author.name + " gaind 1 xp at " + message.server.id)
总之,它基本上打开了一个文件,其中包含字典{ServerID:{Player1ID:xp,Player2ID:xp,etc},etc}
,并且每次有人说话时添加1个xp。我有多服务器支持的多服务器ID。出于某种原因,我得到了这个确切的错误:
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\discord\client.py", line 307, in _run_event
yield from getattr(self, event)(*args, **kwargs)
File "C:\Users\User\Python\Confusion Bot\bot.py", line 83, in on_message
add_xp(server_id, message.author.id, 1)
File "C:\Users\User\Python\Confusion Bot\bot.py", line 43, in add_xp
dicts[server_id] = {user_id:xp}
IndexError: cannot fit 'int' into an index-sized integer
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\User\Python\Confusion Bot\bot.py", line 35, in add_xp
data = dicts[server_id]
IndexError: cannot fit 'int' into an index-sized integer
据我所知,您的文件包含字典的字符串表示形式。当你加载它时,你会得到一个字符串。您需要解析该字符串,以便能够将其作为字典索引,否则您只需对该字符串进行索引(以获取单个字符,尽管听起来您的
server\u id
int太大)。你也许可以用eval
(或者更好的是,ast.literal\u eval
)来解决这个问题,但是更好的解决方法可能会涉及到更好的数据格式(比如json
、yaml、pickle等等)。@Blckknght你所说的eval
或者ast.literal\u eval
是什么意思?我确实把它换成了json,但也遇到了同样的问题。我尽量不使用pickle,因为我希望能够轻松读取文件并在普通编辑器中进行更改。当您打开时(“cache/”+file,“r”).read()
,您会得到一个字符串,而不是字典。要将字符串转换为dict,可以使用eval
(但是ast.literal\u eval
更安全)。@Blckknght非常感谢!这非常有效。您应该使用json.load
和json.dump
并重新编写DICT以使用字符串作为键。看看我在做什么。通过只加载一次dict,在_ready的过程中,我们避免了将一个可能较大的文件读入一个与我们已有的dict相同的dict的情况。