编写Python程序,从score.json读取成绩数据,计算本人成绩的平均学分绩点(保留两位小数)、学分加权平均成绩(保留两位小数)、必修课程曾不及格学分,并保存到Excel文件中,名称为score.xlsx
时间: 2024-10-15 16:07:29 浏览: 28
爬虫_python_一款抓取成绩并计算平均学分绩的程序
在Python中,我们可以使用`json`模块读取JSON文件,`pandas`处理数据,`openpyxl`或`xlsxwriter`库来写入Excel。以下是一个示例程序:
```python
import json
import pandas as pd
# 1. 读取 JSON 文件
def read_score_json(file_name):
with open(file_name, 'r') as f:
data = json.load(f)
return data
# 2. 计算学生成绩
def calculate_average(data):
grades = [item['grade'] for item in data]
credits = [item['credit'] for item in data]
# 平均学分绩点 (GPA)
gpa = sum(grade * credit for grade, credit in zip(grades, credits)) / sum(credits)
# 学分加权平均成绩
weighted_avg = sum(grade * credit for grade, credit in zip(grades, credits))
# 找出必修课中曾不及格的学分
required_courses = [item for item in data if item.get('required', False)]
failed_credits = len([grade for grade in [g['grade'] for g in required_courses] if grade < 60])
return round(gpa, 2), round(weighted_avg, 2), failed_credits
# 3. 写入 Excel
def write_to_excel(df, output_file):
df.to_excel(output_file, index=False)
# 使用函数
data = read_score_json('score.json')
average_gpa, weighted_avg, failed_credits = calculate_average(data)
# 将结果整理成 DataFrame
df = pd.DataFrame(data=[{'Average GPA': average_gpa, 'Weighted Average Score': weighted_avg, 'Failed Credits in Required Courses': failed_credits}])
output_file = 'score.xlsx'
write_to_excel(df, output_file)
阅读全文