file:
1月:3000 2月:1000 3月:4000 4月:8000 5月:10000 6月:12000 7月:17000 8月:4000 9月:6000 10月:5000
1. 读模式打开文件
filename=f"D:\test.txt"
#with open("D:/test.txt",mode='r',encoding='utf-8') as f:
with open(file="notebook", mode='r', encoding='utf-8') as f:
content=f.read() #打印文件原文
content=f.readline() 读入第一行
content=f.readlines() 读入多行存入列表
打印列表:
['1月:3000\n', '2月:1000\n', '3月:4000\n', '4月:8000\n', '5月:10000\n', '6月:12000\n', '7月:17000\n', '8月:4000\n', '9月:6000\n', '10月:5000']
2. 替换换行符,并逐个apend生成新列表
new_list = []
for con in content:
newcontent = con.replace("\n","")
new_list.append(newcontent)
new_list :
['1月:3000', '2月:1000', '3月:4000', '4月:8000', '5月:10000', '6月:12000', '7月:17000', '8月:4000', '9月:6000', '10月:5000']
3. 获取列表末尾元素并append生成money数组,可以int或float类型,用于做图
money=newcontent.split(":")[-1]
new_list.append(newcontent)
money_list.append(float(money))
[3000.0, 1000.0, 4000.0, 8000.0, 10000.0, 12000.0, 17000.0, 4000.0, 6000.0, 5000.0]
4. 删除空行line.strip()
求和,求均值
count=0
for money in money_list:
count +=money
print(sum)--内嵌函数, 均值可以累加或使用内嵌函数
print("平均值1:",count/len(new_list)) avg=sum(money_list)/len(new_list) print("平均值2:",avg) print(count)
5. 简单作图
import numpy as np
import matplotlib.pyplot as plt
from pylab import mpl # 设置显示中文字体
mpl.rcParams["font.sans-serif"] = ["SimHei"]
mpl.rcParams["axes.unicode_minus"] = False
x = [1,2,3,4,5,6,7,8,9,10]
y = money_list
plot = plt.plot(x,y,'r')
plt.title('销售额graph')
plt.xlabel('month')
plt.ylabel('money')
plt.legend(labels=['test']) #指定label避免报错
plt.show()