学习信息按照score排序-python

在这里插入图片描述

# -*- coding:utf-8 -*-
#__author__ = 'YYY'
import re

PATH = r'C:\Users\tester\Desktop\sd.txt'

def read_file(path):
    """
    read sd.txt,return list
    :param path:
    :return:
    """
    stu_list = []
    with open(PATH, 'r', ) as f:
        for i in f.readlines():
            stu_list.append(i)
    return stu_list


def _modify_data(stu_list:list):
    """
    [xx,xx] to [{'name':'xxx','score':'90'}],remove spaces and line breaks
    :param stu_list:
    :return:
    """
    stu_list_new = []
    for i in stu_list:
        stu_dict = dict()
        ###get name,and score values
        name = re.search('name:(.*);', i)
        score = re.search('score.*:(.*\d*)', i)
        if name and score:
            stu_dict['name'] = (name.group(1)).strip()
            stu_dict['score'] = (score.group(1)).strip()
            stu_list_new.append(stu_dict)
    return stu_list_new

def _score_sort(stu_list_new):
    """
    according to score ,and sort,[{'name':'xxx','score':'90'},{'name':'xxx','score':'60'}]
    :param stu_list_new:
    :return:
    """
    score_list = []
    for i in stu_list_new:
        score_list.append(int(i['score']))
    ###score_list ,sorted order
    score_list_new = sorted(score_list, reverse=True)
    ####according to score_list ,sort
    last_stu = []
    for i in score_list_new:
        for j in stu_list_new:
            print(j)
            if i == int(j['score']):
                last_stu.append(j)
    return last_stu

def _standard_format(last_stu):
    """
    name :align left ,score:center,score values :right
    :param last_stu:
    :return:
    """
    last_stu_list = []
    for i in last_stu:
        new_name = 'name:' + i['name']
        new_scroe = ';score:'
        ###str --align left:ljust;right---rjust:#左对齐'{:<10}'.format(t),,
        ####表示居中、左对齐、右对齐,后面紧跟填充的宽度。format(text, '^20')居中,右对齐format(text, '>20')
        ####函数format()可以同时格式化多个值:'{:>10} {:>10}'.format('Hello', 'World')
        new_str = new_name.ljust(20) + new_scroe + i['score'].rjust(10)
        last_stu_list.append(new_str)
    return last_stu_list

def gen_file(path,last_stu_list):
    """
    generate file
    :param path:
    :param last_stu_list:
    :return:
    """
    with open(path,'w') as f:
        for i in last_stu_list:
            f.write(i)
            f.write('\n')

stu_list = read_file(PATH)
stu_list_new = _modify_data(stu_list)
last_stu =_score_sort(stu_list_new)
last_stu_list =_standard_format(last_stu)
gen_file(r'C:\Users\tester\Desktop\sd-new.txt',last_stu_list)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值