您的位置:首页 > 编程语言 > Python开发

Head First Python代码实践(第六章)有注释

2017-12-06 19:19 330 查看
import os
os.chdir('./support_file')

#清洗数据
def sanitize(time_string):
if '-' in time_string:
splitter = '-'
elif ':' in time_string:
splitter = ':'
else:
return (time_string);
(min, secs) = time_string.split(splitter)
return (min + '.' + secs)
'''
#将数据读到程序并转换为列表
def get_coach_data (filename):
    try:
        with open(filename) as f:
            data = f.readline()
        return (data.strip().split(','))
    except IOError as ioerr:
        print('File Err:' + str(ioerr))
        return (None)
'''
'''
#优化后的get_coach_data
def get_coach_data (filename):
    try:
        with open(filename) as f:
            data = f.readline()
        templ = data.strip().split(",")  #在一次性创建字典前创建一个临时列表存放数据
        return ({'Name':templ.pop(0),  #字典创建成为函数一部分
                  'Dob':templ.pop(0),
                  'Time':str(sorted(set(sanitize(t) for t in templ))[0:3])})  #获取前三个时间也作为函数一部分
    except IOError as ioerr:
        print('File Err:' + str(ioerr))
        return (None)
james = get_coach_data('james2.txt')
print(james['Name'] + "'s fastest times are:" + james['Time'])'''
'''#(james_name, james_dob) = james.pop(0), james.pop(0)
# print(james_name + "'s fastest times are:" + str(sorted(set([sanitize(t) for t in james]))[0:3]))
#通过字典实现上两行
james_data = {}
james_data['Name'] = james.pop(0)
james_data['Dob'] = james.pop(0)
james_data['Time'] = james
print(james_data['Name'] + "'s fastest times are:" + str(sorted(set([sanitize(t) for t in james]))))'''
'''
#创建字典
cleese = {}
# print(type(cleese))
palin = dict()
# print(type(palin))
cleese['Name'] = 'John Cleese'
cleese['Occupations'] = ['actor', 'comedian', 'writer', 'file producer']
palin = {'Name':'Michael Palin', 'Occupations': ['comedian', 'actor', 'writer', 'tv']}
#动态添加
palin['Birthplace'] = "Broomhill, shff, England"
cleese['Birthplace'] = "Weston, North, England"
print(palin['Name'])
print(cleese['Occupations'][1])
print(palin)
print(cleese)'''
'''利用类将代码与代码处理的数据相关联(示例)
class Athlete:
    def __init__(self, a_name, a_dob = None, a_time = []):
        self.name = a_name
        self.dob = a_dob
        self.time = a_time
#创建唯一的对象实例,会继承Athlete的特性
james = Athlete('james jhons')
print(type(james))
print(james) #内存地址
print(james.name)  #点记法获得属性值'''
'''利用类对本章例子进行优化'''
class Athlete:
def __init__(self, a_name, a_dob = None, a_time = []):
self.name = a_name
self.dob = a_dob
self.time = a_time
def top3(self):
return (sorted(set(sanitize(t) for t in self.time))[0:3])
###将参数追加到现有的计时列表
def add_time(self, time_value):
self.time.append(time_value)
###用参数列表扩展现有的计时列表
def add_time(self, list_of_time):
self.time.extend(list_of_time)

'''
vera = Athlete('vera_vava')
print(type(vera))
vera.add_time(['0.48'])
print(vera.time)
print(vera.top3())
vera.add_time(['2.22', '1-21', '2:22'])
print(vera.time)
print(vera.top3())'''
'''继承内置list类
class NameList (list):
    def __init__(self, a_name):
        list.__init__([])
        self.name = a_name
johnny = NameList ("John Paul")
print(type(johnny))
print(dir(johnny))
print(johnny)
johnny.append("zhangsan")
johnny.extend(["lisi", 'wangwu'])
print(johnny)
for each_t in johnny:
    print(each_t)'''
'''使用继承内置list类的方式重写Athlete类'''
class AthleteList(list):
def __init__(self, a_name, a_dob=None, a_time=[]):
list.__init__([])
self.name = a_name
self.dob = a_dob
self.extend(a_time) ###数据本身是计时数据,所以不再需要time属性
def top3(self):
return(sorted(set([sanitize(t) for t in self]))[0:3])

# vera = AthleteList('huluwa','2017-10')
# print(vera.dob)
# vera.append('1.01')
# print(vera.top3())

def get_coach_data (filename):
try:
with open(filename) as f:
data = f.readline()
templ = data.strip().split(",")  #在一次性创建字典前创建一个临时列表存放数据
#return (Athlete(templ.pop(0), templ.pop(0), templ))
return (AthleteList(templ.pop(0), templ.pop(0), templ))
except IOError as ioerr:
print('File Err:' + str(ioerr))
return (None)

james = get_coach_data('james2.txt')
print(james.name + "'s fastest times are:" + str(james.top3()))
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python