我有一个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:06:08
这是一种获取值的方法,使用regex。
import re
# Extract the details present inside "|(26.7)c" and convert to float.
with open("numaralar.txt") as f:
    # "re.findall" extracts all the values that match the pattern
    vals = [float(x) for x in re.findall("\|(.*)c", f.read())]
# vals = [25.1, 25.1, 25.2, 25.3]
# Use in-built function to get the required values.
print("Min:", min(vals))
print("Max:", max(vals))
print("Avg:", sum(vals)/len(vals))发布于 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)发布于 2020-05-23 17:40:53
你可以不用regex就能解决这个问题,但有点痛苦。您必须在管道|上拆分并在之后获取所有内容,然后在c上将其拆分,并在此之前获取所有内容。
with open("numaralar.txt") as f:
    vals = [float(line.split('|')[1].split('c')[0]) for line in f]
# vals = [25.1, 25.1, 25.2, 25.3]
# Use in-built function to get the required values.
print("Min:", min(vals))
print("Max:", max(vals))
print("Avg:", sum(vals)/len(vals))不过,在处理所有列时,拆分更有意义,例如:
with open("test.txt") as f:
    for line in f:
        time, data = line.strip().split('|')
        temp, humidity = data.split(',')
        temp = float(temp.rstrip('c'))
        humidity = float(humidity.rstrip('%rh'))
        print(time, temp, humidity)https://stackoverflow.com/questions/61975549
复制相似问题