繁体   English   中英

如何从该文本文件中读取字典?

[英]How to read a dictionary from this text file?

我对python还是很陌生,我正在玩将数据保存到文本文件的过程。 我的问题是,当我尝试访问字典时,会出现此错误TypeError: string indices must be integers但是我不知道如何转换它们。

这是我文件中的内容:

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()

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

我建议使用JSON将数据写到文本文件https://docs.python.org/3/library/json.html

您可以使用json.dumps方法创建可写入文件的JSON数据,并使用json.loads方法将文件中的文本转换回字典中

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

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

书架是永久存储字典并随时更改/编辑字典的好工具。 我目前正在将它用于我正在进行的一个不一致的bot项目,到目前为止,它很棒。

这是一些使用入门的技巧(直接从我链接的页面中提取)。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM