I’m trying to read a txt file with informations about time, temperature and humidity, this is the shape
JavaScript
x
5
1
07:54:03.383 -> Humidity:38.00%;Temperature:20.50°C;Heat index:19.60°C;
2
07:59:03.415 -> Humidity:37.00%;Temperature:20.90°C;Heat index:20.01°C;
3
08:04:03.435 -> Humidity:37.00%;Temperature:20.90°C;Heat index:20.01°C;
4
08:09:03.484 -> Humidity:37.00%;Temperature:20.80°C;Heat index:19.90°C;
5
I would like to extrapolate, for each line, the 4 informations and plot them in a graph. using open() and fileObject.read() i can plot the txt into VSC Terminal, but i don’t know how to:
- read the time and save it in a proper way (it’s splitted by “:”)
- read the values, for example i could think to read the first 5 characters after “Humidity” word, the first 5 after “Temperature” and so on. For each line
- store them in proper vector and then plot the 3 path in function of the time. I’m using numpy as library.
Advertisement
Answer
Assuming you can tolerate reading your data into a Python string, we can use re.findall
here:
JavaScript
1
11
11
1
# -*- coding: utf-8 -*-
2
import re
3
4
inp = """07:54:03.383 -> Humidity:38.00%;Temperature:20.50°C;Heat index:19.60°C;
5
07:59:03.415 -> Humidity:37.00%;Temperature:20.90°C;Heat index:20.01°C;
6
08:04:03.435 -> Humidity:37.00%;Temperature:20.90°C;Heat index:20.01°C;
7
08:09:03.484 -> Humidity:37.00%;Temperature:20.80°C;Heat index:19.90°C;"""
8
9
vals = re.findall(r'^(d{2}:d{2}:d{2}(?:.d+)?) -> Humidity:(d+(?:.d+)?)%;Temperature:(d+(?:.d+)?)°C;Heat index:(d+(?:.d+)?)°C;', inp, flags=re.M)
10
print(vals)
11
This prints:
JavaScript
1
5
1
[('07:54:03.383', '38.00', '20.50', '19.60'),
2
('07:59:03.415', '37.00', '20.90', '20.01'),
3
('08:04:03.435', '37.00', '20.90', '20.01'),
4
('08:09:03.484', '37.00', '20.80', '19.90')]
5