1. 程式人生 > >《Head First Python》 第七章 Web開發之——資料建模 (電子書247-250)

《Head First Python》 第七章 Web開發之——資料建模 (電子書247-250)

資料建模

說人話:就是解決如何把原始的文字形式的資料檔案,轉換成按照預先定製類的一個個例項的方法,從而方便使用者呼叫、處理。

資料儲存與呼叫

上圖來自《head First Python》P247

這裡寫圖片描述

上圖來自《head First Python》P249

實現——資料儲存和訪問

資料儲存和訪問是有兩個函式實現的:
put_to_store()函式
get_from_store()函式。

  • put_to_store()函式

返回值:

  1. AthleteList字典,包含Athlete物件;
  2. 將AthleteList寫入pickle中;

程式碼:

def put_to_store(files_list):
    all_athletes = {}
    #定義字典,用於儲存運動員物件
    for each_file in files_list:
        #get_coach_data(each_file)開啟檔案列表中的每一個檔案,
        #並將其轉換成AthleteList物件。
        #最後,將AthleteList物件存入all_athletes字典。
        ath = get_coach_data(each_file)
        all_athletes[ath.name] = ath
    try
: #開啟athletes.pickle檔案,將字典 all_athletes存入其中。 with open('athletes.pickle','wb') as athf: pickle.dump(all_athletes, athf) except IOError as ioerr: print('File error(put_to_store):' + str(ioerr)) return(all_athletes)
  • get_from_store()函式

返回值:

  1. AthleteList字典,包含Athlete物件;

程式碼:

def get_from_store():
    all_athletes = {}
    try:
        #開啟athletes.pickle檔案,它是一個字典
        #然後,將其賦值給字典all_athletes。
        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)

驗證——資料儲存和訪問

負責儲存和訪問資料的程式碼模組(athletemodel.py)如下:

# -*- coding:utf-8 -
'''
Created on 2017-1-3

@author: lenovo
'''
import pickle
from athletelist import AthleteList

def get_coach_data(filename):
    try:
        with open(filename) as jaf:
            data=jaf.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(put_to_store):' + str(ioerr))
    return(all_athletes)

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

Ok,來驗證一下!

在IDLE中,開啟athletemodel.py,按F5執行,然後,輸入命令dir(),將會看到:

>>> dir()
['AthleteList', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'get_coach_data', 'get_from_store', 'pickle', 'put_to_store']

dir()的作用是什麼呢?

“Python中內建的dir()函式用於列出一個定義物件的識別符號。例如,對於一個模組,包括在模組中定義的函式,類和變數。當你給dir()提供一個模組名字時,它返回在那個模組中定義的名字的列表。當沒有為其提供引數時, 它返回當前模組中定義的變數、屬性、方法的列表。”

因此,我們可以發現,通過輸入dir()它返回了當前模組中定義的方法、屬性和變數的列表。

Ok,工具有了,我們設定要讀取並存儲的檔案:

>>> the_files = ['sarah2.txt','james2.txt','mikey2.txt','julie2.txt']

儲存資料:

>>> data = put_to_store(the_files)

檢視一下:

>>> data
{'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'], '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'], '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']}

果然,呼叫函式put_to_store(the_files)後,將文字檔案轉換成了字典。

資料儲存好了(轉換成例項了),下面來訪問吧:

呼叫get_from_store()函式

>>> data_copy = get_from_store()

函式返回字典給data_copy,然後可以訪問:

>>> data_copy = get_from_store()
>>> for each_athlete in data_copy:
    print(data_copy[each_athlete].name + ' ' + data_copy[each_athlete].dob)
    #注意呼叫的格式,字典中的每一個數據項都是AthleteList的物件


James Lee 2002-3-14
Sarah Sweeney 2002-6-17
Julie Jones 2002-8-17
Mikey McManus 2002-2-24

Ok,至此,有關資料的儲存和讀取方法告一段落。另,第一次用Markdown寫文件,確實很簡潔、很好用;對比word中需要反覆調整格式,真的是太方便了,感謝開發者!!