简体   繁体   English

从文本中读取部分行

[英]Reading part of lines from a txt

I'm trying to read a txt file with informations about time, temperature and humidity, this is the shape我正在尝试读取一个包含时间、温度和湿度信息的 txt 文件,这是形状

07:54:03.383 -> Humidity:38.00%;Temperature:20.50°C;Heat index:19.60°C;
07:59:03.415 -> Humidity:37.00%;Temperature:20.90°C;Heat index:20.01°C;
08:04:03.435 -> Humidity:37.00%;Temperature:20.90°C;Heat index:20.01°C;
08:09:03.484 -> Humidity:37.00%;Temperature:20.80°C;Heat index:19.90°C;

I would like to extrapolate, for each line, the 4 informations and plot them in a graph.我想在图表中为每一行推断 4 个信息和 plot 个信息。 using open() and fileObject.read() i can plot the txt into VSC Terminal, but i don't know how to:使用 open() 和 fileObject.read() 我可以将 txt plot 放入 VSC 终端,但我不知道如何:

  • 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.读取值,例如我可以考虑读取“湿度”字样后的前 5 个字符,“温度”字样后的前 5 个字符,依此类推。 For each line对于每一行
  • store them in proper vector and then plot the 3 path in function of the time.将它们存储在适当的向量中,然后 plot 时间的 function 中的 3 路径。 I'm using numpy as library.我正在使用 numpy 作为图书馆。

Assuming you can tolerate reading your data into a Python string, we can use re.findall here:假设您可以容忍将数据读入 Python 字符串,我们可以在这里使用re.findall

# -*- coding: utf-8 -*-
import re

inp = """07:54:03.383 -> Humidity:38.00%;Temperature:20.50°C;Heat index:19.60°C;
07:59:03.415 -> Humidity:37.00%;Temperature:20.90°C;Heat index:20.01°C;
08:04:03.435 -> Humidity:37.00%;Temperature:20.90°C;Heat index:20.01°C;
08:09:03.484 -> Humidity:37.00%;Temperature:20.80°C;Heat index:19.90°C;"""

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)
print(vals)

This prints:这打印:

[('07:54:03.383', '38.00', '20.50', '19.60'),
 ('07:59:03.415', '37.00', '20.90', '20.01'),
 ('08:04:03.435', '37.00', '20.90', '20.01'),
 ('08:09:03.484', '37.00', '20.80', '19.90')]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM