平均值,每天.Python



所以,我有这个文件.txt,我必须计算每天的平均温度,文件.txt要大得多,所以有很多天

data : 2021-05-01 16:52:13.074093
Temperature: 25.20 C
Pressure:    986.57 hPa 
Altitude:    224.50 
data : 2021-05-01 16:52:18.129364
Temperature: 25.20 C
Pressure:    986.55 hPa 
Altitude:    224.61 

我做了平均数,但我不知道每天该怎么做这是迄今为止的代码

def temperature():
print("The average temperature is:")
total = 0.0
c = 0
with open("text.txt", 'r') as f:
for line in f:
if "Temperature" not in line: continue
temp = line.split(" ")[1]
total =total+ float(temp)
c =c+ 1
print(total / c)
def temperature():
print("The average temperature is:")
total = 0.0
c = 0
alltemp=[]
with open(r"C:VMremove it.txt", 'r') as f:
for line in f:
if "Temperature" not in line: continue
temp = line.split(" ")[1]
total =total+ float(temp)
c =c+ 1
alltemp.append(total / c)
print(total / c)
return alltemp

alltemp将为您提供列表中的所有温度

这里有一种在纯Python中实现的方法:

def temperature():
temperatures = {}
with open("text.txt", 'r') as f:
for line in f:
if "data" in line:
day = line.split(" ")[2].strip()
if "Temperature" in line:
temp = float(line.split(" ")[1])
if day in temperatures:
temperatures[day].append(temp)
else:
temperatures[day] = [temp]
for key,value in temperatures.items():
print("Mean temperature on {} was {}".format(key, sum(value)/len(value)))

想法:假设日期总是在温度之前,我们可以依次读取,先读取日期,然后读取温度。

当你遇到一个";数据";(date?(行,split(或regex(只保留日期,并将其用作填写字典的键。这些值是当天的温度列表。完成后,每天迭代字典,计算平均值(当天温度列表的总和除以长度(。

我的答案中有一些硬编码的值。你的文件有点"破碎的";(日期行被称为"数据"?行与行之间的冒号不一致,data :temperature:(,因此请确保split中的位置正确。如果不能保证正则表达式在整个文件中保持一致,请使用正则表达式。

由于日期和温度在不同的行,您的代码需要记住当前(最后一次出现(的日期。然后你可以将每天的温度分组,例如在字典中:

from collections import defaultdict
temp_per_day = defaultdict(list)
current_day = None
total = count = 0
for line in f:
if line[:4] == 'data':
current_day = line.split()[2]
elif 'Temperature' in line:
temp = float(line.split()[1])
total += temp
count += 1
temp_per_day[current_day].append(temp)

然后,你可以迭代每天的温度值,并计算平均值:

for day, temps in temp_per_day.items():
avg_temp = sum(temps) / len(temps)
print(f'average temperature on {day} is {avg_temp:.2f}')

最新更新