如何解决在制作字典之前剥离?
我正在制作一个文本文件的字典(在 python 中),格式如下:
动物类型/休眠/唤醒时间/睡眠时间/喂食时间
每条新线都有一种新的动物。这是到目前为止的代码:
def read_animals_from_file(file_name):
'''
Makes a dictionary with the animals as keys and their attributes as values
:param file_name: Name of the file with information
:return: Dictionary with the animals and their attributes
'''
fobj = open(file_name,"r")
for line in fobj:
key,value1,value2,value3,value4 = line.split("/")
animal_dict[key] = value1,int(value2),int(value3),value4
print(animal_dict)
return animal_dict
问题是每一行的最后一个值都包含“\n”。这是字典的样子:
{'熊':('冬天',9,20,' 12\n'),
'大黄蜂':('冬天',6,23,' -\n'),
'驼鹿': (' - ',7,19,' 10'),
'猫头鹰': (' - ',21,5,' 21\n'),
'海狮':(' - ',18,' 14\n'),
'密封': (' - ',
'狼':(' - ',' 12\n')}
我想我应该在创建字典之前去掉 \n,但我似乎无法让它工作。我也很好奇如何访问特定值,因为我认为它们位于所谓的元组 (?) 中。比如我只想打印起床时间怎么办?对于初学者可能出现的错误,我深表歉意:)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。