• 为数据建模


    把文本文件中的数据转换为AthleteList对象实例,存储在一个字典中(按选手索引),然后保存为一个pickle文件。

    # Author kevin_hou
    import pickle
    from athletelist import AthleteList
    
    def get_coach_data(filename):
            try:
                with open(filename) as f:
                    data = f.readline()
                    temp1 = data.strip().split(',')
                    return (AthleteList(temp1.pop(0), temp1.pop(0), temp1))
            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) #将各个文件转换为一个AthleteList对象实例,并把选手的数据增加到字典。
            all_athletes[ath.name] = ath #每个选手的名字作为字典的"键","值"是AthleteList对象实例
        try:
            with open('athletes.pickle', 'wb') as athf:
                pickle.dump(all_athletes, athf)  #将整个AthleteList增加到一个pickle中
        except IOError as ioerr:    #不要忘记用一个try/except来保护你的文件I/O代码
            print('File error (put_and_store):' + str(ioerr))
        return (all_athletes)
    
    def get_from_store():
        all_athletes = {}
        try:
            with open('athletes.pickle', 'rb') as athf:
                all_athletes = pickle.load(athf) #只需将整个pickle读入字典
        except IOError as ioerr:
            print('File error(get_from_store):' + str(ioerr))
            return (all_athletes)
    print(dir())
    #['AthleteList', '__annotations__', '__builtins__', '__cached__',
    # '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__',
    # 'get_coach_data', 'get_from_store', 'pickle', 'put_to_store']
    
    the_files = ['sarah.txt', 'james.txt', 'mikey.txt', 'julie.txt']
    data = put_to_store(the_files)
    print(data)
    #{'Sarah Sweeney': ['2.58', '2:39', '2-25', '2-25', '2:54', '2.18', '2:55', '2:55'],
    # 'James Lee': ['3:21', '2:34', '2.45', '3.01', '2:01', '2:01', '3:10', '2:22'],
    # 'Mikey': ['3.01', '3:01', '3.02', '3:02', '3.02', '3:22', '2.49', '2:38'],
    #  'Julie Jones': ['2.11', '2:11', '2:23', '3:10', '2:23', '3:10', '3:21', '3-21']}
    
    for each_athlete in data:
        print(data[each_athlete].name + '' + data[each_athlete].dob)
    
    # Sarah Sweeney2002-6-17
    # James Lee2002-3-4
    # Mikey McManus 2002-2-24
    # Julie Jones 2002-8-17
    

     

  • 相关阅读:
    CTE SQL Server 转
    论坛搜索网站技术概述 供参考
    SQL 存储过程 数据分页源代码
    sql server中使用convert来取得datetime数据类型样式(全)
    SQL Server 2008系统信息查询常用命令 查看表大小、记录数等
    用正则表达式匹配HTML\XML等文件中的标签
    使用.Net访问Office编程接口
    不显示某字段有重复的记录 SQL语句
    操作XMLC#(转)
    关于CASE中使用聚合函数时的一点经验
  • 原文地址:https://www.cnblogs.com/kevin-hou1991/p/13701304.html
Copyright © 2020-2023  润新知