python入门编程100例(011-020)

Python学习 专栏收录该内容
26 篇文章 5 订阅
"""
p011:学生成绩的排序
"""
if __name__ == '__main__':
    students = [
        {"sno": 101, "sname": "小张", "sgrade": 88},
        {"sno": 102, "sname": "小王", "sgrade": 99},
        {"sno": 103, "sname": "小李", "sgrade": 77},
        {"sno": 104, "sname": "小赵", "sgrade": 66},
    ]
    
    students_sort = sorted(students, key=lambda x: x["sgrade"], reverse=True)

    print(f"source {students} , sort result:{students_sort}")

"""
p012:读取文件实现排序
"""
def read_file():
    reulst = []
    with open("./p012_student_grade.txt", encoding="utf-8") as fp:
        for line in fp:
            line = line[:-1]
            line = line.split(",")
            line[2] = int(line[2])
            reulst.append(line)
    return reulst

def sort_grades(datas):
    result = sorted(datas, key=lambda x: x[2])
    return result

def wirte_file(datas):
    with open("./p012_student_grade2.txt", mode="w", encoding="utf-8") as fp:
        for item in datas:
            item[2] = str(item[2])
            line = ','.join(item) + "\n"
            fp.write(line)


if __name__ == '__main__':
    # 读取文件
    datas = read_file()
    print(datas)

    # 排序数据
    datas = sort_grades(datas)
    print(datas)

    # 写入文件
    wirte_file(datas)


101,小张,66
102,小李,44
103,小周,77
104,小赵,88
105,小王,99
106,小余,55
107,小强,22
"""
p013:计算学生的最高分,最低分,平均分
"""
def compute_score():
    scores = []
    with open("./p013_students_grade_file.txt", encoding="utf-8") as fp:
        for line in fp:
            line = line[:-1]
            field = line.split(',')
            scores.append(int(field[-1]))
    max_score = max(scores)
    min_score = min(scores)
    avg_score = round(sum(scores) / len(scores), 2)
    return max_score, min_score, avg_score


if __name__ == '__main__':
    max_score, min_score, avg_score = compute_score()
    print(f"mx_score = {max_score}, min_score = {min_score}, avg_score = {avg_score}")
"""
p014:统计英文文章的单词数目
"""
if __name__ == '__main__':
    word_count = {}
    with open('./p014_article.txt', encoding="utf-8") as fp:
        for line in fp:
            line = line[:-1]
            words = line.split()
            for word in words:
                if word not in word_count:
                    word_count[word] = 0
                word_count[word] += 1
    print(
    sorted(word_count.items(), key=lambda x: x[1], reverse=True)[:10]
    )
"""
p015:统计目录下的所有文件大小
"""

import os


if __name__ == '__main__':
    sum_size = 0
    for file in os.listdir("."):
        if os.path.isfile(file):
            sum_size += os.path.getsize(file)
    print(f"all size of dir:", sum_size/1024)
"""
p016:使用文件后缀整理文件夹
"""
import os
import shutil

if __name__ == '__main__':
    dir = "./p016_arrange_dir"
    for file in os.listdir(dir):
        ext = os.path.splitext(file)[1]
        ext = ext[1:]
    
        if not os.path.isdir(f"{dir}/{ext}"):
            os.mkdir(f"{dir}/{ext}")
    
        # print(file, ext)
        source_path = f"{dir}/{file}"
        target_path = f"{dir}/{ext}/{file}"
    
        shutil.move(source_path, target_path)

 

"""
p017:递归搜索目录中最大的文件
"""
import os


if __name__ == '__main__':
    search_dir = "E:\学习"
    result_files = []
    for root, dirs, files in os.walk(search_dir):
        for file in files:
            file_path = os.path.join(root, file)
            result_files.append((file_path, os.path.getsize(file_path)/1024))

    print(sorted(result_files, key=lambda x: x[1], reverse=True)[:10])
"""
p018:计算不同课程的最高分,最低分,平均分
"""

if __name__ == '__main__':
    course_grade = {}
    with open("./p018_course_students_grade.txt", encoding="utf-8") as fp:
        for line in fp:
            line = line[:-1]
            course, sno, sname, grade = line.split(",")
            # print(course, sno, sname, grade)
            if course not in course_grade:
                course_grade[course] = []
            course_grade[course].append(int(grade))

    # print(course_grade)

    for course, grades in course_grade.items():
        print(course, max(grades), min(grades), round(sum(grades)/len(grades), 2))
语文,101,小张,66
语文,102,小李,88
语文,103,小周,67
语文,104,小赵,89
语文,105,小王,75
数学,101,小张,87
数学,102,小李,55
数学,103,小周,99
数学,104,小赵,48
数学,105,小王,58
英语,101,小张,64
英语,102,小李,95
英语,103,小周,66
英语,104,小赵,57
英语,105,小王,68
"""
p019:实现不同文件的关联
"""

if __name__ == '__main__':
    course_teacher_map ={}
    with open("./p019_teacher_name.txt", encoding="utf-8") as fp:
        for line in fp:
            line = line[:-1]
            course, teacher = line.split(",")
            course_teacher_map[course] = teacher

    print(course_teacher_map)

    with open("./p019_course_students_grade.txt", encoding="utf-8") as fp:
        for line in fp:
            line = line[:-1]
            course, sno, sname, sgrade = line.split(",")
            teacher = course_teacher_map[course]
            print(course, teacher, sno, sname, sgrade)
语文,101,小张,66
语文,102,小李,88
语文,103,小周,67
语文,104,小赵,89
语文,105,小王,75
数学,101,小张,87
数学,102,小李,55
数学,103,小周,99
数学,104,小赵,48
数学,105,小王,58
英语,101,小张,64
英语,102,小李,95
英语,103,小周,66
英语,104,小赵,57
英语,105,小王,68
语文,周老师
数学,赵老师
英语,李老师
"""
p020:批量合并多个text文件
"""
import os
if __name__ == '__main__':
    dir = "./p020_many_texts"
    contents = []
    for file in os.listdir(dir):
        file_path = os.path.join(dir, file)
        if os.path.isfile(file_path) and file.endswith(".txt"):
            with open(file_path, encoding="utf-8") as fp:
                contents.append(fp.read())
       
    # print(contents)
    final_content = "\n".join(contents)
    
    with open(dir+"/many_texts.txt", mode="w", encoding="utf-8") as fp:
        fp.write(final_content)

 

  • 5
    点赞
  • 5
    评论
  • 81
    收藏
  • 打赏
    打赏
  • 扫一扫,分享海报

评论 5 您还未登录,请先 登录 后发表或查看评论
©️2022 CSDN 皮肤主题:技术黑板 设计师:CSDN官方博客 返回首页

打赏作者

指尖魔法师

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值