为数据建模

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# 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

 

 

posted @   JRS077  阅读(145)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示