Home Backend Development Python Tutorial 从零学python系列之数据处理编程实例(二)

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

Jun 16, 2016 am 08:44 AM
python

在上一节从零学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()))

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Two Point Museum: All Exhibits And Where To Find Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the conversion speed fast when converting XML to PDF on mobile phone? Is the conversion speed fast when converting XML to PDF on mobile phone? Apr 02, 2025 pm 10:09 PM

The speed of mobile XML to PDF depends on the following factors: the complexity of XML structure. Mobile hardware configuration conversion method (library, algorithm) code quality optimization methods (select efficient libraries, optimize algorithms, cache data, and utilize multi-threading). Overall, there is no absolute answer and it needs to be optimized according to the specific situation.

Is there any mobile app that can convert XML into PDF? Is there any mobile app that can convert XML into PDF? Apr 02, 2025 pm 08:54 PM

An application that converts XML directly to PDF cannot be found because they are two fundamentally different formats. XML is used to store data, while PDF is used to display documents. To complete the transformation, you can use programming languages ​​and libraries such as Python and ReportLab to parse XML data and generate PDF documents.

How to convert XML files to PDF on your phone? How to convert XML files to PDF on your phone? Apr 02, 2025 pm 10:12 PM

It is impossible to complete XML to PDF conversion directly on your phone with a single application. It is necessary to use cloud services, which can be achieved through two steps: 1. Convert XML to PDF in the cloud, 2. Access or download the converted PDF file on the mobile phone.

What is the function of C language sum? What is the function of C language sum? Apr 03, 2025 pm 02:21 PM

There is no built-in sum function in C language, so it needs to be written by yourself. Sum can be achieved by traversing the array and accumulating elements: Loop version: Sum is calculated using for loop and array length. Pointer version: Use pointers to point to array elements, and efficient summing is achieved through self-increment pointers. Dynamically allocate array version: Dynamically allocate arrays and manage memory yourself, ensuring that allocated memory is freed to prevent memory leaks.

How to control the size of XML converted to images? How to control the size of XML converted to images? Apr 02, 2025 pm 07:24 PM

To generate images through XML, you need to use graph libraries (such as Pillow and JFreeChart) as bridges to generate images based on metadata (size, color) in XML. The key to controlling the size of the image is to adjust the values ​​of the <width> and <height> tags in XML. However, in practical applications, the complexity of XML structure, the fineness of graph drawing, the speed of image generation and memory consumption, and the selection of image formats all have an impact on the generated image size. Therefore, it is necessary to have a deep understanding of XML structure, proficient in the graphics library, and consider factors such as optimization algorithms and image format selection.

How to open xml format How to open xml format Apr 02, 2025 pm 09:00 PM

Use most text editors to open XML files; if you need a more intuitive tree display, you can use an XML editor, such as Oxygen XML Editor or XMLSpy; if you process XML data in a program, you need to use a programming language (such as Python) and XML libraries (such as xml.etree.ElementTree) to parse.

How to convert xml into pictures How to convert xml into pictures Apr 03, 2025 am 07:39 AM

XML can be converted to images by using an XSLT converter or image library. XSLT Converter: Use an XSLT processor and stylesheet to convert XML to images. Image Library: Use libraries such as PIL or ImageMagick to create images from XML data, such as drawing shapes and text.

Recommended XML formatting tool Recommended XML formatting tool Apr 02, 2025 pm 09:03 PM

XML formatting tools can type code according to rules to improve readability and understanding. When selecting a tool, pay attention to customization capabilities, handling of special circumstances, performance and ease of use. Commonly used tool types include online tools, IDE plug-ins, and command-line tools.

See all articles