打开储存学生成绩的文件score.txt并计算总成绩 用matplotlib画柱状统计图
时间: 2024-02-28 19:52:28 浏览: 17
好的,以下是一个示例代码,可以读取score.txt中的学生成绩,并计算总成绩,并用matplotlib绘制柱状统计图:
```python
import matplotlib.pyplot as plt
# 打开文件score.txt并读取学生成绩
with open('score.txt', 'r') as f:
lines = f.readlines()
# 计算总成绩
total_score = 0
for line in lines:
score = int(line.strip())
total_score += score
# 输出总成绩
print('总成绩:', total_score)
# 绘制柱状统计图
scores = [int(line.strip()) for line in lines]
plt.hist(scores, bins=10, edgecolor='black')
plt.xlabel('成绩')
plt.ylabel('人数')
plt.title('学生成绩分布')
plt.show()
```
在这个示例中,我们首先使用open()函数打开score.txt文件,并使用readlines()方法读取文件中的内容。然后,我们使用一个循环计算所有学生的总成绩。接下来,我们使用matplotlib的hist()函数绘制柱状统计图,其中,bins参数指定了柱子的个数,edgecolor参数指定了柱子的边框颜色,xlabel和ylabel参数分别指定了x轴和y轴的标签,title参数指定了图表的标题。最后,我们使用show()方法显示图表。