打包代码与数据
FileName="F:\\book\\python\\headfirst python book&&code\\code\\chapter6\\data\\sarah2.txt"
def sanitize(time_string):
if ":" in time_string:
min,sec=time_string.split(":")
elif "-" in time_string:
min,sec=time_string.split("-")
if 'min' in locals():
return min+"."+sec
else:
return time_string
def get_coach_data(fileName):
try:
with open(fileName) as f:
data=f.readline().strip().split(',')
#字典的创建与初始化
cachData={"name":data.pop(0),"dob":data.pop(0),"times":str([sorted(set([sanitize(item) for item in data]))[0:3]])}
return cachData
except IOError as err:
print("File error "+str(err))
return (None)
sportRecord=get_coach_data(FileName)
#字典的访问
FileName="F:\\book\\python\\headfirst python book&&code\\code\\chapter6\\data\\sarah2.txt"
def sanitize(time_string):
if ":" in time_string:
min,sec=time_string.split(":")
elif "-" in time_string:
min,sec=time_string.split("-")
if 'min' in locals():
return min+"."+sec
else:
return time_string
self.name=a_name
self.dob=a_dob
self.times=a_times
def top3(self):
return sorted(set([sanitize(item) for item in self.times]))[0:3]
def add_time(self,t):
self.times.append(t)
def add_times(self,ts):
self.times.extend(ts)
def get_coach_data(fileName):
try:
with open(fileName) as f:
data=f.readline().strip().split(',')
return Athlete(data.pop(0),data.pop(0),data)
except IOError as err:
print("File error "+str(err))
return (None)
sportRecord=get_coach_data(FileName)
print(sportRecord.name+"'s fastest times are:"+str(sportRecord.top3()))
sportRecord.add_time("2.17")
print(sportRecord.name+"'s fastest times are:"+str(sportRecord.top3()))
sportRecord.add_times(["2.15","2.16"])
print(sportRecord.name+"'s fastest times are:"+str(sportRecord.top3()))
FileName="F:\\book\\python\\headfirst python book&&code\\code\\chapter6\\data\\sarah2.txt"
def sanitize(time_string):
if ":" in time_string:
min,sec=time_string.split(":")
elif "-" in time_string:
min,sec=time_string.split("-")
if 'min' in locals():
return min+"."+sec
else:
return time_string
"""
class Athlete:
def __init__(self,a_name,a_dob=None,a_times=[]):
self.name=a_name
self.dob=a_dob
self.times=a_times
def top3(self):
return sorted(set([sanitize(item) for item in self.times]))[0:3]
def add_time(self,t):
self.times.append(t)
def add_times(self,ts):
self.times.extend(ts)
self.extend(a_times)
self.name=a_name
self.dob=a_dob
def top3(self):
return sorted(set([sanitize(item) for item in self]))[0:3]
def get_coach_data(fileName):
try:
with open(fileName) as f:
data=f.readline().strip().split(',')
return Athlete(data.pop(0),data.pop(0),data)
except IOError as err:
print("File error "+str(err))
return (None)
sportRecord=get_coach_data(FileName)
print(sportRecord.name+"'s fastest times are:"+str(sportRecord.top3()))
sportRecord.append("2.17")
print(sportRecord.name+"'s fastest times are:"+str(sportRecord.top3()))
sportRecord.extend(["2.15","2.16"])
print(sportRecord.name+"'s fastest times are:"+str(sportRecord.top3()))