我是python
的新手,一直在从事一个项目,在该项目中,我必须将.txt
文件中的数据组织到dictionary
(字典的键值应该是该人的全名,而其他数据是字典形式的值)中的dictionary
必须包括——
item
location
date of purchase
remarks
salespeople
.txt
文档如下所示:
Jimothy Donovan
Guitar
California
20.6.2018
The frame is broken
ENDREMARK
Hank Pym
Daniel Bennet
X
Isaac Newton
Hourglass
San Jose
12.8.2019
The hourglass is not accurate anymore
would like replacement
ENDREMARK
Daniel Bennet
Ethan Cole
X
代码如下所示:
def process_data(file: TextIO) -> Dict:
CustomerDataDict = {}
lines = file.readline().strip()
x = 0
for line in file:
key = lines[x].strip()
CustomerDataDict[key[0]] = lines[x+1].strip()
CustomerDataDict[key[1]] = lines[x+2].strip()
CustomerDateDict[key[2]] = lines[x+3].strip()
start = lines.index('ENDREMARK\n')
list_remark = lines[3:start]
full_remark = ''
for n in list_remark:
full_remark += n
CustomerDataDict[key[3]] = full_remark
end = lines.index('X\n')
salesppl_list = lines[start + 1:end]
salespeople = []
for name in salesppl_list:
following.append(name.strip())
CustomerDataDict[key[4]] = salespeople
x = end + 1
return CustomerDataDict
Dictionary
的格式应为:
{username:
{'item':itemname,
'location':location,
'date-of-purchase': DATE,
'remarks':remarks,
'salespeople': {names of salespeople}
}
}
感谢您的帮助
您可以在文本行上使用迭代器,并根据您的结构进行遍历:
只要数据符合预期结构,这将生成所需的字典
[编辑]不使用中断语句的备用版本(毕竟不是那么糟糕):
相关问题 更多 >
编程相关推荐