Requirements: Create text files with the names of james, julie, mikey, and sarah to store their respective scores. The time format is accurate to minutes. The shorter the time, the better the score, output the first three best scores for each student without duplicates, And the Separators for the second should be unified as "."
Data preparation: create four text files respectively
James.txt 2-34,3: 21, 2.34, 2.45, 3.01, 2-22
Julie.txt 2.59, 2.11, 3-10, 2-3.21, 3: 10, 3-21
Mikey.txt, 3.01, 3.02, 3.02, 2.49
Sarah.txt, 2.58, 2-25, 2-55, 2: 54, 2.18
Code implementation:
Copy codeThe Code is as follows:
Import OS
OS. chdir ('C: \ Python33 \ HeadFirstPython \ hfpy_code \ chapter5 ') # change the workspace to the directory where the file is located
# Define the function get_filedata to take values from the file
Def get_filedata (filename ):
Try:
With open (filename) as f: # with statement to open and automatically close a file
Data = f. readline () # Read characters from the file line by line
Return (data. strip (). split (',') # clear spaces between characters and separate them with commas
Handle t IOError as ioerr:
Print ('file error' + str (ioerr) # handle exceptions and print errors
Return (None)
# Define the function modify_time_format to unify the time expression in all files into "Minute. Second"
Def modify_time_format (time_string ):
If "-" in time_string:
Splitter = "-"
Elif ":" in time_string:
Splitter = ":"
Else:
Splitter = "."
(Mins, secs) = time_string.split (splitter) # Use the separator splitter to separate characters and then store them into mins and secs respectively.
Return (mins + '.' + secs)
# Define the get_prev_three function to return the top three non-repeated time scores in the file
Def get_prev_three (filename ):
New_list = [modify_time_format (each_t) for each_t in get_filedata (filename)] # Use List derivation to generate a new list of records after unified time expression
Delete_repetition = set (new_list) # use the set function to delete repeated items in the new list and generate a new set.
In_order = sorted (delete_repetition) # sort new sets without repeatability using the copy sort sorted Function
Return (in_order [0: 3]) # return the first three items in the list
# Output the top three non-repeated time scores of the corresponding files
Print (get_prev_three ("james.txt "))
Print (get_prev_three ("julie.txt "))
Print (get_prev_three ("mikey.txt "))
Print (get_prev_three ("sarah.txt "))
Output result:
Copy codeThe Code is as follows:
['2. 01', '2. 22', '2. 34']
['2. 11', '2. 23', '2. 59']
['2. 22', '2. 38', '2. 49']
['2. 18', '2. 25', '2. 39 ']