gpt4 book ai didi

python - 如何从这个文本文件中读取字典?

转载 作者:行者123 更新时间:2023-12-01 01:37:05 24 4
gpt4 key购买 nike

我对 python 还很陌生,我正在尝试将数据保存到文本文件。我的问题是,当我尝试访问字典时,它会出现此错误 TypeError:字符串索引必须是整数 但我不知道如何转换它们。

这是我的文件中的内容:

Student 1/:{ "Topic 1" : 0,"Topic 2" : 0,"Topic 3" : 0,"Topic 4" : 4}
Student 2/:{ "Topic 1" : 1,"Topic 2" : 2,"Topic 3" : 0,"Topic 4" : 0}
Student 3/:{ "Topic 1" : 1,"Topic 2" : 0,"Topic 3" : 0,"Topic 4" : 1}

这是我的代码:

import ast #I thought this would fix the problem

def main():
data = {}
with open("test.txt") as f:
for line in f:
content = line.rstrip('\n').split('/:')
data[content[0]] = ast.literal_eval(content[1])
f.close()
print(data["Student 1"["Topic 1"]]) # works if I only do data[Student 1]

main()

是否有更有效的数据存储方式?

最佳答案

既然你的问题要求“一种更有效的数据存储方式”,我会说是的!

https://docs.python.org/3/library/shelve.html

Shelve 是一个很好的工具,可以持久存储词典并随时更改/编辑词典。我目前正在将它用于我正在开发的一个 Discord 机器人项目,到目前为止,效果非常好。

这里有一些入门使用提示(直接从我链接的页面中提取)。

import shelve

d = shelve.open(filename) # open -- file may get suffix added by low-level
# library

d[key] = data # store data at key (overwrites old data if
# using an existing key)
data = d[key] # retrieve a COPY of data at key (raise KeyError
# if no such key)
del d[key] # delete data stored at key (raises KeyError
# if no such key)

flag = key in d # true if the key exists
klist = list(d.keys()) # a list of all existing keys (slow!)

# as d was opened WITHOUT writeback=True, beware:
d['xx'] = [0, 1, 2] # this works as expected, but...
d['xx'].append(3) # *this doesn't!* -- d['xx'] is STILL [0, 1, 2]!

# having opened d without writeback=True, you need to code carefully:
temp = d['xx'] # extracts the copy
temp.append(5) # mutates the copy
d['xx'] = temp # stores the copy right back, to persist it

# or, d=shelve.open(filename,writeback=True) would let you just code
# d['xx'].append(5) and have it work as expected, BUT it would also
# consume more memory and make the d.close() operation slower.

d.close() # close it

关于python - 如何从这个文本文件中读取字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52302453/

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