现在我的手里有了新的一组数据,数据内容如下:
james.txt:
James Lee,2002-3-14,2-34,3:21,2.34,2.45,3.01,2:01,2:01,3:10,2-22,2-01,2.01,2:16
julie.txt:
Julie Jones,2002-8-17,2.59,2.11,2:11,2:23,3-10,2-23,3:10,3.21,3-21,3.01,3.02,2:59
mikey.txt:
Mikey McManus,2002-2-24,2:22,3.01,3:01,3.02,3:02,3.02,3:22,2.49,2:38,2:40,2.22,2-31
sarah.txt:
Sarah Sweeney,2002-6-17,2:58,2.58,2:39,2-25,2-55,2:54,2.18,2:55,2:55,2:22,2-21,2.22
我们可以看到数据格式为姓名,出生年月和一系列的时间列表,现在希望的是打印每个文件中的人的姓名、出生年月和最快的三个时间。现在我们先编写一段简单的代码来实现这个功能,代码如下:
"""转换时间格式"""
def sanitize(time_string):
if '-' in time_string:
splitter='-'
elif ':' in time_string:
splitter=':'
else:
return(time_string)
(mins,secs)=time_string.split(splitter)
return(mins+'.'+secs)
"""读取文件内容,并按逗号进行拆分"""
def get_coach_data(filename):
try:
with open(filename) as file:
data = file.readline()
return(data.strip().split(','))
except IOError as error:
print('File Error:'+str(error))
return(None)
"""读取sarah.txt的内容"""
sarah = get_coach_data('sarah.txt')
"取出姓名和生日"
(sarah_name,sarah_birthday) = sarah.pop(0),sarah.pop(0)
"""打印姓名、生日和最快的三个时间"""
print(sarah_name+"的生日是:"+sarah_birthday+