Python:简单处理表格和图片数据并初步分析

目录

         1.需求:

2.表格示例:

3.安装第三方库

4.代码实现 :


1.需求:

8.对周五面试结果excel表格进行操作 20分
  输出所有同学“名称:对应成绩”的信息  2分
  输出分值最高和最低的同学名称及分数,(如有重复并列输出)3分
  求出平均值并输出 2分
  输出高于平均值的同学名称及成绩 3分
  输出低于平均值的同学名称及成绩 3分
  将成绩排名信息写入csv格式的文件中,文件名称为:test_你自己的名字_时间戳.csv 3分
  生成一个图片,将前三名信息水印在这张图片上,将图片保存在 4分
2.表格示例:

3.安装第三方库

        pip install pandas numpy openpyxl

4.代码实现 :
import os
import time
import numpy
import pandas as pd
from PIL import ImageFont, ImageDraw, Image


abs_path = os.path.abspath(__file__)


def add_watermark(image_path, text, font_path, font_size=40, fill=(45, 123, 65, 128)):
    """
    在图片上添加水印
    :param image_path: 图片路径
    :param text: 水印文本
    :param font_path: 字体文件路径
    :param font_size: 字体大小,默认为 40
    :param fill: 水印颜色,默认为白色半透明
    :return: None
    """
    # 忘记参考网站了,此处是照搬完成需求
    with Image.open(image_path) as image:
        # 加载图片获得画笔
        draw = ImageDraw.Draw(image)
        width, height = image.size
        font = ImageFont.truetype(font_path, font_size)
        text_width, text_height = draw.textsize(text, font=font)
        x = int((width - text_width) / 2)
        y = int((height - text_height) / 2)
        draw.text((x, y), text, font=font, fill=fill)
        image.save(image_path)


def write_image(score_info):
    # 参考:https://blog.csdn.net/weixin_45240714/article/details/123233036
    # 设置字体,可以默认
    font = ImageFont.truetype("C:\WINDOWS\FONTS\MSYHL.TTC", 20)

    # 打开即将编辑的图片
    imageFile = "6.png"
    tp = Image.open(imageFile)

    # 在图片上添加文字
    draw = ImageDraw.Draw(tp)
    draw.text((100, 100), score_info, (255, 255, 0), font=font)
    tp.save("n.png")


def get_name_score():
    print("面试成绩输出单:")
    # content.items()  获取到每列,附带序号
    # 可以使用skip row 跳过某一行
    content = pd.read_excel('f.xlsx')
    name = [] # 学生姓名存储列表
    score = [] # 学生成绩存储列表
    real_score = []  # 用来存储有效的成绩
    real_name_score = []  # 用来存储最终有效的姓名和成绩
    max_name_score = [] # 大于平均值的数据列表
    min_name_score = [] # 小于平均值的数据列表
    for item in content.items():
        # 判断列开头以此获取指定列内容
        if item[0].startswith('2209A-P11'):
            for n in item[1]:
                name.append(n)
        else:
            for s in item[1]:
                score.append(s)
                if type(s) in [int, float]:
                    real_score.append(s)
    # 将读出来的数据利用zip函数进行重新组合
    name_score = zip(name, score)
    # zip 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。
    # 平均值利用numpy实现
    score_avg = int(numpy.mean(real_score))
    print("成绩平均值是:{0}".format(score_avg))
    score_min = min(real_score)
    print("成绩最低为:{0} 分".format(score_min))
    score_max = max(real_score)
    print("成绩最高值为:{0} 分".format(score_max))
    for ns in name_score:
        if ns[1] == score_max:
            max_name_score.append(f"姓名:{ns[0]},成绩为:{ns[1]}")
        elif ns[1] == score_min:
            min_name_score.append(f"姓名:{ns[0]},成绩为:{ns[1]}")
        if type(ns[1]) in [int, float]:
            # 可以直接使条件
            # if int(ns[1]) > score_avg:
            #     score_gt_avg.append(f"姓名:{ns[0]},成绩为:{ns[1]}")
            # elif int(ns[1]) < score_avg:
            #     score_lt_avg.append(f"姓名:{ns[0]},成绩为:{ns[1]}")
            real_name_score.append([ns[0], ns[1]])
    # 也可以使用filter函数进行过滤
    # score_gt_avg = filter(lambda x: x[1] > score_avg, real_name_score)
    # score_gt_avg = [i for i in score_gt_avg]
    # 也可以使用列表推导式
    score_gt_avg = [i for i in real_name_score if i[1] > score_avg]
    score_lt_avg = [i for i in real_name_score if i[1] < score_avg]

    # 按照需求输出
    print("成绩最高的同学:{0}".format(';'.join(max_name_score)))
    print("成绩最低的同学:{0}".format(';'.join(min_name_score)))
    print("高于平均成绩的同学有:{0} 人".format(len(score_gt_avg)))
    print("高于平均成绩的同学有:", score_gt_avg)
    print("低于于平均成绩的同学有:{0} 人".format(len(score_lt_avg)))
    print("高于平均成绩的同学有:", score_lt_avg)

    # 输出到csv
    csv_name = "test_顺子老师_" + str(int(time.time())) + ".csv"
    if not os.path.exists(csv_name):
        content.to_csv(csv_name, header=['', ''], index=False, mode='w')
    # 排序并生成字符串
    sorted_real_name_score = sorted(real_name_score, key=lambda x: x[1], reverse=True)
    print(sorted_real_name_score)
    # 利用切片获取前三名和后三名,如果是在pandas里面可以使用head等方法
    final_score = sorted_real_name_score[:3] + sorted_real_name_score[-3:]
    final_score_str = []
    for score in final_score:
        final_score_str.append(score[0] + ':' + str(score[1]))

    #  图片上写字
    write_image(';'.join(final_score_str))

    # 图片水印
    add_watermark('s3.png', ';'.join(final_score_str), "C:\WINDOWS\FONTS\MSYHL.TTC", font_size=15,
                  fill=(123, 0, 0, 128))

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

千码君2016

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

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

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

打赏作者

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

抵扣说明:

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

余额充值