利用Python实现从五个含有学号姓名成绩的TXT文件中,成绩文件已发至微信群中,每个文件代表一次成绩,总共五次,统计出每个人成绩最高的三次分数,分别为成绩1,成绩2,成绩3,并将学号姓名与3次最高成绩结果保存在一个excel文件中
时间: 2023-12-10 16:41:47 浏览: 100
首先,需要安装openpyxl库,用于操作Excel文件。可以使用pip命令进行安装。
```python
pip install openpyxl
```
然后,读取五个TXT文件中的成绩信息,并将其存储在一个字典中。字典的键为学号,值为一个列表,保存该学生的姓名和五次成绩。在读取每个TXT文件时,需要逐行解析文件内容,提取学号、姓名和成绩信息,并将其存储在字典中。
```python
import os
data = {}
for i in range(1, 6):
filename = f"score{i}.txt"
with open(filename, "r") as f:
for line in f:
parts = line.strip().split()
if len(parts) == 3:
sno, name, score = parts
if sno not in data:
data[sno] = [name, [], [], [], [], []]
data[sno][i].append(int(score))
```
接下来,需要统计每个人的最高成绩,并将其存储在一个新的字典中。在遍历原始数据字典时,对于每个学生,计算其最高的三次成绩,并将其存储在新的字典中。
```python
top_scores = {}
for sno, info in data.items():
scores = info[1:]
top_scores[sno] = sorted([max(scores[i]) for i in range(5)], reverse=True)[:3]
```
最后,将学号、姓名和最高三次成绩保存在一个Excel文件中。首先,需要创建一个新的Excel文件,并创建一个工作表。然后,依次写入每个学生的信息。
```python
from openpyxl import Workbook
workbook = Workbook()
worksheet = workbook.active
worksheet.append(["学号", "姓名", "成绩1", "成绩2", "成绩3"])
for sno, info in data.items():
name = info[0]
scores = top_scores[sno]
row = [sno, name] + scores
worksheet.append(row)
workbook.save("top_scores.xlsx")
```
完整代码如下:
```python
import os
from openpyxl import Workbook
data = {}
for i in range(1, 6):
filename = f"score{i}.txt"
with open(filename, "r") as f:
for line in f:
parts = line.strip().split()
if len(parts) == 3:
sno, name, score = parts
if sno not in data:
data[sno] = [name, [], [], [], [], []]
data[sno][i].append(int(score))
top_scores = {}
for sno, info in data.items():
scores = info[1:]
top_scores[sno] = sorted([max(scores[i]) for i in range(5)], reverse=True)[:3]
workbook = Workbook()
worksheet = workbook.active
worksheet.append(["学号", "姓名", "成绩1", "成绩2", "成绩3"])
for sno, info in data.items():
name = info[0]
scores = top_scores[sno]
row = [sno, name] + scores
worksheet.append(row)
workbook.save("top_scores.xlsx")
```
阅读全文