HF-chapter7 为数据建模

本文介绍了一个用于管理运动员成绩数据的Python模块AthleteList。该模块能够读取文件中的运动员信息,并提供存储和检索功能。通过使用pickle模块进行序列化,可以将数据持久化存储到磁盘上,便于后续的数据管理和分析。


构造模块

模块athletelist并安装。模块athletelist 内容如下:

class AthleteList(list):
    def __init__(self,a_name,a_dob=None,a_times=[]):
        list.__init__([])
        self.name=a_name
        self.dob=a_dob
        self.extend(a_times)
    
    def tops3(self):
        return(sorted(set([sanitize(t)for t in self]))[0:3])


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 f:
            data=f.readline()
        templ=data.strip().split(',')
        return(AthleteList(templ.pop(0),templ.pop(0),templ))
    except IOError as ioerr:
        print('File Error: ' + str(ioerr))
        return (None)
数据的存储和取出
import pickle
from athletelist import AthleteList
import os

def get_coach_data(filename):
        try:
            with open(filename) as f:
                data=f.readline()
            templ=data.strip().split(',')
            return(AthleteList(templ.pop(0),templ.pop(0),templ))
        except IOError as ioerr:
            print('File Error: ' + str(ioerr))
        return (None)
    
def put_to_store(files_list):
    all_athletes={}
    for each_file in files_list:
        ath=get_coach_data(each_file)
        all_athletes[ath.name]=ath
    try:
        with open('athletes.pickle','wb') as athf:
            pickle.dump(all_athletes,athf)
    except IOError as ioerr:
        print('File Error: ' + str(ioerr))
    return (all_athletes)

def get_from_store():
    all_athletes={}
    try:
        with open('athletes.pickle','rb') as athf:
            all_athletes=pickle.load(athf)
    except IOError as ioerr:
        print('File Error:(get_from_store): ' + str(ioerr))
    return(all_athletes)

os.chdir('D:/HeadFirstPython/webapp/data')
os.getcwd()
the_files=['sarah.txt','julie.txt','james.txt','mikey.txt']
data=put_to_store(the_files)
print(data)
data_copy=get_from_store()
for each_athlete in data_copy:
    print(data_copy[each_athlete].name + ' '+data_copy[each_athlete].dob)

查看输出:

RESTART: C:/Users/ThinkPad/AppData/Local/Programs/Python/Python36-32/chapter7/c7-223.py 
{'Sarah Sweeney': ['2:58', '2.58', '2:39', '2-25', '2-55', '2:54', '2.18', '2:55', '2:55', '2:22', '2-21', '2.22'], 'Julie Jones': ['2.59', '2.11', '2:11', '2:23', '3-10', '2-23', '3:10', '3.21', '3-21', '3.01', '3.02', '2:59'], 'James Lee': ['2-34', '3:21', '2.34', '2.45', '3.01', '2:01', '2:01', '3:10', '2-22', '2-01', '2.01', '2:16'], 'Mikey McManus': ['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 Sweeney 2002-6-17
Julie Jones 2002-8-17
James Lee 2002-3-14
Mikey McManus 2002-2-24
>>> dir()
['AthleteList', '__annotations__', '__builtins__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'data', 'each_athlete', 'get_coach_data', 'get_from_store', 'os', 'pickle', 'put_to_store', 'the_files']


                
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值