我打开一个文件,其中每行代表一个学生的信息。 存储方式如下:
41097-xxkx:Johansson Elin:TE20:290
每个值都用":"
分隔,下一行是new student,依此类推
通过这个,我将把这些值加到一个dict中,这样每个学生都会得到一个dict“prsnummer”,“namn”等等。然后,这些指令将存储在一个列表中
# How I think about dealing with it.
# Tho stripping every part, and adding to dict was harder.
with open("text.txt", "r") as f:
for line in f:
"""
Do something
"""
# How txt files look like. Each value is seperated with a :
# 040512-xxkx:Valek Kevin:TE20:280
# 041097-xxkx:Johansson Elin:TE20:290
# In the end it will look like:
list_of_dicts = [
{"prsnummer" : "040512-xxkx", "namn" : "Valek Kevin", "Klass" : "TE20", "Merit" : "280"},
{"prsnummer" : "041097-xxkx", "namn" : "Johansson Elin", "Klass" : "TE20", "Merit" : "290"}
]
# (Merit is meant to be stored as a str)
这是相当大的进步
基本上,您可以解析行,将字符串拆分为“:”字符,然后根据列表位置提取信息
例如,在char
":"
上拆分字符串"040512-xxkx:Valek Kevin:TE20:280"
,将生成这个values
列表您需要拆分冒号上的行,然后使用上面为每行列出的键构造一个字典
相关问题 更多 >
编程相关推荐