Head First Python--读入字符串文件、替换、排序、去重以及使用函数

import os
import pickle
import nester

os.chdir('d:/Python_test/ch5')

def sanitize(time_string):
    if '-' in time_string:
        splitter = '-'
    elif ':' in time_string:
        splitter = ':'
    else:
        return time_string
    (mins, secs) = time_string.split(splitter)
    return(mins + '.' + secs)

try:
    with open('james.txt') as james_file:
        data = james_file.readline()
        James = data.strip().split(',')
    with open('sarah.txt') as sarah_file:
        data = sarah_file.readline()
        Sarah = data.strip().split(',')
    with open('julie.txt') as julie_file:
        data = julie_file.readline()
        Julie = data.strip().split(',')
    with open('mikey.txt') as mikey_file:
        data = mikey_file.readline()
        Mikey = data.strip().split(',')
except IOError as err:
    print('File error! ' + str(err))

print(sorted(set([sanitize(each_t) for each_t in James]))[0:3])
print(sorted(set([sanitize(each_t) for each_t in Sarah]))[0:3])
print(sorted(set([sanitize(each_t) for each_t in Julie]))[0:3])
print(sorted(set([sanitize(each_t) for each_t in Mikey]))[0:3])

 

你可能感兴趣的:(Python)