从零学python系列之数据处理编程实例(二)


Posted in Python onMay 22, 2014

在上一节从零学python系列之数据处理编程实例(一)的基础上数据发生了变化,文件中除了学生的成绩外,新增了学生姓名和出生年月的信息,因此将要成变成:分别根据姓名输出每个学生的无重复的前三个最好成绩和出生年月

数据准备:分别建立四个文本文件

              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

 在上一节基础上,修改部分代码,将新要求实现如下:

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(',')   #将字符间的空格清除后,用逗号分隔字符
            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])
                    })                                #使用字典将关联的姓名,出生年月,时间键和值进行存储并返回
    except IOError as ioerr:
        print ('File Error' + str(ioerr))     #异常处理,打印错误
        return (None)
#定义函数modify_time_format将所有文件中的时分表达方式统一为“分.秒”
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函数删除新列表中重复项,并生成新的集合
    in_order=sorted(delete_repetition)                                                               #采用复制排序sorted函数对无重复性的新集合进行排序
    return (in_order[0:3])      
#输出james的排名前三的不重复成绩和出生年月
james = get_filedata('james2.txt')
print (james["name"]+"'s fastest times are: " + james["times"])
print (james["name"] + "'s birthday is: "  + james["date_of_birth"])
#输出julie的排名前三的不重复成绩和出生年月
julie = get_filedata('julie2.txt')
print (julie["name"]+"'s fastest times are: " + julie["times"])
print (julie["name"] + "'s birthday is: "  + julie["date_of_birth"])
#输出mikey的排名前三的不重复成绩和出生年月
mikey = get_filedata('mikey2.txt')
print (mikey["name"]+"'s fastest times are: " + mikey["times"])
print (mikey["name"] + "'s birthday is: "  + mikey["date_of_birth"])
#输出sarah的排名前三的不重复成绩和出生年月
sarah = get_filedata('sarah2.txt')
print (sarah["name"]+"'s fastest times are: " + sarah["times"])
print (sarah["name"] + "'s birthday is: "  + sarah["date_of_birth"])

通过建立继承内置list的类AthleteList,将方法定义在类中实现相同功能:

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 in self]))[0:3])
def get_filedata(filename):
    try:
        with open(filename)  as f:        #with语句打开和自动关闭文件
            data=f.readline()                 #从文件中逐行读取字符
            data_list=data.strip().split(',')   #将字符间的空格清除后,用逗号分隔字符
            return(
                   AthleteList(data_list.pop(0), data_list.pop(0), data_list)
                   )                                #使用字典将关联的姓名,出生年月,时间键和值进行存储并返回
    except IOError as ioerr:
        print ('File Error' + str(ioerr))     #异常处理,打印错误
        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 are: " + str(james.get_prev_three()))
julie = get_filedata('julie2.txt')
print (julie.name+"'s fastest times are: " + str(julie.get_prev_three()))
mikey = get_filedata('mikey2.txt')
print (mikey.name+"'s fastest times are: " + str(mikey.get_prev_three()))
sarah = get_filedata('sarah2.txt')
print (sarah.name+"'s fastest times are: " + str(sarah.get_prev_three()))
Python 相关文章推荐
详解Python开发中如何使用Hook技巧
Nov 01 Python
python中in在list和dict中查找效率的对比分析
May 04 Python
Python格式化输出%s和%d
May 07 Python
python的pandas工具包,保存.csv文件时不要表头的实例
Jun 14 Python
获取Pytorch中间某一层权重或者特征的例子
Aug 17 Python
Python中的引用和拷贝实例解析
Nov 14 Python
利用Python计算KS的实例详解
Mar 03 Python
Python selenium爬取微博数据代码实例
May 22 Python
Keras中的两种模型:Sequential和Model用法
Jun 27 Python
python实现取余操作的简单实例
Aug 16 Python
Python调用Redis的示例代码
Nov 24 Python
python中的random模块和相关函数详解
Apr 22 Python
从零学python系列之数据处理编程实例(一)
May 22 #Python
Python学习笔记_数据排序方法
May 22 #Python
从零学Python之hello world
May 21 #Python
Python开发实例分享bt种子爬虫程序和种子解析
May 21 #Python
从零学Python之引用和类属性的初步理解
May 15 #Python
python中xrange和range的区别
May 13 #Python
Python中os和shutil模块实用方法集锦
May 13 #Python
You might like
PHP分页效率终结版(推荐)
2013/07/01 PHP
php实现的漂亮分页方法
2014/04/17 PHP
php获取发送给用户的header信息的方法
2015/03/16 PHP
php json相关函数用法示例
2017/03/28 PHP
Yii框架的布局文件实例分析
2019/09/04 PHP
javascript 面向对象思想 附源码
2009/07/07 Javascript
javascript与webservice的通信实现代码
2010/12/25 Javascript
jquery blockUI 遮罩不能消失与不能提交的解决方法
2011/09/17 Javascript
js 控制图片大小核心讲解
2013/10/09 Javascript
在页面中js获取光标/鼠标的坐标及光标的像素坐标
2013/11/11 Javascript
javascript的数组和常用函数详解
2014/05/09 Javascript
探讨js字符串数组拼接的性能问题
2014/10/11 Javascript
jQuery实现ctrl+enter(回车)提交表单
2015/10/19 Javascript
浅谈JavaScript 中有关时间对象的方法
2016/08/15 Javascript
vue.js+boostrap项目实践(案例详解)
2016/09/21 Javascript
AngularJS ng-repeat指令中使用track by子语句解决重复数据遍历错误问题
2017/01/21 Javascript
jquery实现tab键进行选择后enter键触发click行为
2017/03/29 jQuery
ES6新特性六:promise对象实例详解
2017/04/21 Javascript
如何将HTML字符转换为DOM节点并动态添加到文档中详解
2018/08/19 Javascript
layui radio点击事件实现input显示和隐藏的例子
2019/09/02 Javascript
js实现GIF图片的分解和合成
2019/10/24 Javascript
[00:43]FTP典藏礼包 DOTA2三大英雄霸气新套装
2014/03/21 DOTA
利用Python批量压缩png方法实例(支持过滤个别文件与文件夹)
2017/07/30 Python
详解python3 + Scrapy爬虫学习之创建项目
2019/04/12 Python
Django打印出在数据库中执行的语句问题
2019/07/25 Python
python Popen 获取输出,等待运行完成示例
2019/12/30 Python
TensorFLow 数学运算的示例代码
2020/04/21 Python
keras的ImageDataGenerator和flow()的用法说明
2020/07/03 Python
python使用scapy模块实现ping扫描的过程详解
2021/01/21 Python
python3.9.1环境安装的方法(图文)
2021/02/02 Python
canvas因为图片资源不在同一域名下而导致的跨域污染画布的解决办法
2019/01/18 HTML / CSS
美国最大的旗帜经销商:Carrot-Top
2018/02/26 全球购物
Microsoft Advertising美国:微软搜索广告
2019/05/01 全球购物
财务人员担保书
2014/05/13 职场文书
租赁协议书
2015/01/27 职场文书
http通过StreamingHttpResponse完成连续的数据传输长链接方式
2022/02/12 Python