如何从txt文件一行的数据制作子字典?



我有这个.txt文件需要转换为字典: (行的顺序可能会有所不同(

name : john doe
age : 23
gender : MALE
address : kendall 6, Miami
career: mechanical engineer
times going : 2
number of assignments : 4
semester : 4
average : 9.2
interests : gaming, robotics, drama movies
availability:
friday : 6:30 - 10:30
sunday : 12:30 - 13:30
monday : 16:30 - 18:30

输出代码应如下所示:


{'name': 'john doe',
'age': '23',
'gender': 'MALE',
'address': 'kendall 6, Miami',
'semester': '4',
'career': 'mechanical engineer',
'average': '9.2',
'times going': '2',
'number of assignments': '5',
'interests': 'gaming, robotics, drama movies',
'availability':
{'friday': (630,1030),
'sunday': (1230,1330),
'monday': (1630,1830)
}
}

至于现在,我已经成功地制作了字典,正好在这个"可用性"部分之前:


dicc={}
listRestrictions=["availability","monday","tuesday","wednesday","thursday","friday","saturday","sunday"]
for line in file:
line = line.strip("n").replace(" : ", ":").strip(" ")
key = line[: line.index(":")]
if key not in listRestrictions:
value = line[line.index(":") + 1 :]
dicc[key] = value
print(dicc)

并打印:

{'name': 'john doe', 'age': '23', 'gender': 'MALE', 'address': 'kendall 6, Miami', 'career': 'mechanical engineer', 'times going': '2', 'number of assignments': '4', 'semester': '4', 'average': '9.2', 'interests': 'gaming, robotics, drama movies'}

(请记住,它可能在.txt文件的任何文件上,并且日期将始终在"可用性"下(...我将如何将"可用性"作为值,然后将日期作为子字典,如上所示?

dicc={}
last_key = ''
for _line in file:
line = _line.strip("n").replace(" : ", ":")
line = line.strip(" ")
key = line[: line.index(":")]
last_key = key
value = line[line.index(":") + 1 :]
if // the first part of the line is a blank space:
dicc[last_key][key] = value
else:
dicc[key] = value
print(dicc)
dicc = {}
for line in file:
isAppended = line.startswith("    ")
line = line.strip("n").replace(" : ", ":").strip(" ")
value = line[line.index(":") + 1 :]
tempKey = line[: line.index(":")]
if len(value)==0:
currKey = tempKey
tempDict = {}
elif isAppended:
tempDict[tempKey] = value
dicc.update({currKey:tempDict})
else:
dicc[tempKey] = value

不知道为什么要尝试这种低级解析。那不是亚姆吗?这个假设让我非常接近:

import yaml
from pprint import pprint
with open('data.txt') as f:
data = yaml.load(f)

那么data这个嵌套的Python字典:

{'name': 'john doe',
'age': 23,
'gender': 'MALE',
'address': 'kendall 6, Miami',
'career': 'mechanical engineer',
'times going': 2,
'number of assignments': 4,
'semester': 4,
'average': 9.2,
'interests': 'gaming, robotics, drama movies',
'availability': {'friday': '6:30 - 10:30',
'sunday': '12:30 - 13:30',
'monday': '16:30 - 18:30'}}

剩下的差异很容易做到,因为它是一个Python数据结构。

我不知道你是如何拉动你的日期和时间的,但假设这些是,例如,以以下格式开始:

days = ['monday', 'tuesday', 'wednesday']
times = [(630, 1030), (830, 1400), (930, 1330)]

然后,构建可用性字典的一种方法如下:

dicc['availability'] = dict(zip(days, times))
print (dicc)

最新更新