我的文件:
目标:读取txt文件并返回字典
我所拥有的:
def load_snacks(snack_file: TextIO) -> Tuple[Dict[str,List[str]],Dict[str,List[str]]]:
"""Return a two-item tuple containing a "healthysnack_to_junkfood" dictionary
and a "healthysnack_to_healthysnack" dictionary with the data from snack_file.
"""
snack_H2J = {}
snack_H2H = {}
line = snack_file.readline().strip()
while line != '':
# due to structure of the file,line contains a healthy snack name
healthysnack_name = line
# properly format the 1st healthy snack name,use helper fcn (see below for helper fcn)
flip_name_and_del_comma(healthysnack_name)
healthy_list = []
junk_list = []
line = snack_file.readline().strip()
while line != '\n':
if ',' in line:
snack_H2J[healthysnack_name] = line
a = flip_name_and_del_comma(line)
healthy_list.append(a)
else:
snack_H2H[healthysnack_name] = line
junk_list.append(line)
line = snack_file.readline().strip()
return (snack_H2J,snack_H2H)
下面是我的助手;我已经验证了这个方法
def flip_name_and_del_comma(s: str) -> str:
""" Retrun a new str that reverses the format name order from 'colour,healthy snack name' to
'healthy snack name to colour'
>>> flip_name_and_del_comma('orange,carrot')
'carrot orange'
>>> flip_name_and_del_comma('yellow,mango')
'mango yellow'
"""
s_reversed = ','.join(reversed(s.split(',')))
s_comma_delete = s_reversed.replace(',',' ')
return s_comma_delete