Example of data processing programming from the zero-learning Python series (II.)

Source: Internet
Author: User
In the previous section from the zero-learning Python series of data Processing programming example (a) based on the change in the document, in addition to the student's results, the new student name and date of birth information, and therefore will become: each student according to the name output of the first three of the best score and date of birth

Data preparation: Create four text files respectively

James2.txt James lee,2002-3-14,2-34,3:21,2.34,2.45,3.01,2:01,2:01,3:10,2-22

Julie2.txt Julie jones,2002-8-17,2.59,2.11,2:11,2:23,3-10,2-23,3:10,3.21,3-21

Mikey2.txt Mikey mcmanus,2002-2-24,2:22,3.01,3:01,3.02,3:02,3.02,3:22,2.49,2:38

Sarah2.txt Sarah sweeney,2002-6-17,2:58,2.58,2:39,2-25,2-55,2:54,2.18,2:55,2:55

On the basis of the previous section, modify some of the code to implement the new requirements as follows:

Copy the Code code as follows:


Import OS
Print (OS.GETCWD ())
Os.chdir (' C:\Python33\HeadFirstPython\hfpy_code\chapter6 ') #将工作空间修改为文件所在的目录

#定义函数get_filedata从文件中取值
def get_filedata (filename):
Try:
with open (filename) as F: #with语句打开和自动关闭文件
Data=f.readline () #从文件中逐行读取字符
Data_list=data.strip (). Split (', ') #将字符间的空格清除后, separating the characters with commas
return ({
"name": Data_list.pop (0),
"Date_of_birth": Data_list.pop (0),
"Times": Str (sorted (Set ([Modify_time_format (s) for s in Data_list]) [0:3])
}) #使用字典将关联的姓名, date of birth, time key and value are stored and returned
except IOError as Ioerr:
Print (' File Error ' + str (IOERR) ) #异常处理, print error
return (None)

#定义函数modify_time_format将所有文件中的时分表达方式统一为 "minute. Seconds"
def modify_time_format (time_ String):
If "-" in time_string:
splitter= "-"
Elif ":" in time_string:
splitter= ":"
Else:
splitter= "."
(mins, secs) =time_string.split (splitter) #用分隔符splitter分隔字符后分别存入mins和secs
return (mins+ '. ' +secs)

#定义函数get_prev_three返回文件中排名前三的不重复的时间成绩
def get_prev_three (filename):
New_list=[modify_time_format (each_t) for each_t in Get_filedata (filename)] #采用列表推导将统一时分表达方式后的记录生成新的列表
Delete_repetition=set (new_list) #采用集合set函数删除新列表中重复项 and generate a new collection
In_order=sorted (delete_repetition) #采用复制排序sorted函数对无重复性的新集合进行排序
Return (In_order[0:3])

#输出james的排名前三的不重复成绩和出生年月
James = Get_filedata (' james2.txt ')
Print (james["name"]+ "s fastest times is:" + james["Times"])
Print (james["name"] + "s birthday is:" + james["Date_of_birth"])

#输出julie的排名前三的不重复成绩和出生年月
Julie = Get_filedata (' julie2.txt ')
Print (julie["name"]+ "s fastest times is:" + julie["Times"])
Print (julie["name"] + "s birthday is:" + julie["Date_of_birth"])

#输出mikey的排名前三的不重复成绩和出生年月
Mikey = Get_filedata (' mikey2.txt ')
Print (mikey["name"]+ "s fastest times is:" + mikey["Times"])
Print (mikey["name"] + "s birthday is:" + mikey["Date_of_birth"])

#输出sarah的排名前三的不重复成绩和出生年月
Sarah = Get_filedata (' sarah2.txt ')
Print (sarah["name"]+ "s fastest times is:" + sarah["Times"])
Print (sarah["name"] + "s birthday is:" + sarah["Date_of_birth"])

By creating a class athletelist that inherits the built-in list, the method definition implements the same functionality in the class:

Copy the Code code as follows:


Import OS
Print (OS.GETCWD ())
Os.chdir (' C:\Python33\HeadFirstPython\hfpy_code\chapter6 ') #将工作空间修改为文件所在的目录

#定义类AthleteList继承python内置的list
Class Athletelist (list):
def __init__ (self, name, Dob=none, times=[]):
LIST.__INIT__ ([])
Self.name=name
Self.dob=dob
Self.extend (Times)
def get_prev_three (self):
Return (sorted (set ([Modify_time_format (t) for t under Self])) [0:3])

def get_filedata (filename):
Try
with open (filename) as F: #with语句打开和自动关闭文件
Data=f.readline () #从文件中逐行读取字符
Data_list=data.strip (). Split (', ') #将字符间的空格清除后, separating characters with commas
Return
Athletelist (Data_list.pop (0), Data_list.pop (0), data_list)
) #使用字典将关联的姓名, date of birth, time key and value are stored and returned
Except IOError as Ioerr:
Print (' File error ' + str (ioerr)) #异常处理, printing error
Return (None)

def modify_time_format (time_string):
If "-" in time_string:
Splitter= "-"
Elif ":" In time_string:
Splitter= ":"
Else
Splitter= "."
(mins, secs) =time_string.split (splitter) #用分隔符splitter分隔字符后分别存入mins和secs
Return (mins+ '. ' +secs)

James = Get_filedata (' james2.txt ')
Print (james.name+ "s fastest times is:" + str (James.get_prev_three ()))

Julie = Get_filedata (' julie2.txt ')
Print (julie.name+ "s fastest times is:" + str (Julie.get_prev_three ()))

Mikey = Get_filedata (' mikey2.txt ')
Print (mikey.name+ "s fastest times is:" + str (Mikey.get_prev_three ()))

Sarah = Get_filedata (' sarah2.txt ')
Print (sarah.name+ "s fastest times is:" + str (Sarah.get_prev_three ()))

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.