我有一个txt文件,其中包含不同类型的读数。我想显示其中一个读数的最小值、最大值和平均值。
txt文件的一个示例输出是
19-05-2020 17:23:15|25.10c,52.00%rh
19-05-2020 17:23:15|25.10c,53.00%rh
19-05-2020 17:23:15|25.20c,54.00%rh
19-05-2020 17:23:15|25.30c,55.00%rh我只想显示摄氏读数的最小值和最大值。
下面有代码,但它读取整个文件。我要它只读摄氏读数。
_min = None
_max = None
_sum = 0
_len = 0
with open('numaralar.txt') as f:
for line in f:
val = int(line.strip())
if _min is None or val < _min:
_min = val
if _max is None or val > _max:
_max = val
_sum += val
_len += 1
_avg = float(_sum) / _len
# Print output
print("Min: %s" % _min)
print("Max: %s" % _max)
print("Avg: %s" % _avg)发布于 2020-05-23 17:02:39
我建议你使用正则表达式来提取芹菜的阅读,类似这样。
[0-9]{1,}\.[0-9]{2}c然后删除“c”并将其转换为浮动。然后,您可以对该数据执行另一项操作。
正则表达式可用于提取具有某种模式的特定字符串段。在你的例子中-数字,点,数字,"c“。
上述模式意味着:
结尾处标记"c“。
请参见如何使用re模块提取此类数据。Python extract pattern matches
readings = [
'19-05-2020 17:23:15|25.10c,52.00%rh',
'19-05-2020 17:23:15|25.10c,53.00%rh',
'19-05-2020 17:23:15|25.20c,54.00%rh',
'19-05-2020 17:23:15|25.30c,55.00%rh'
]
import re
temperatures = []
for reading in readings:
pattern = re.compile('[0-9]{1,}\.[0-9]{2}c')
temperature = pattern.search(reading).group(0)
temperature = temperature[:-1] #removes last character which is "c"
temperature = float(temperature)
temperatures.append(temperature)
print(temperatures)https://stackoverflow.com/questions/61975549
复制相似问题