You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python 3.11读取混合格式时序温度数据并绘图的实现方案

问题解决:仪器时间-温度数据读取与绘图

原代码问题分析

  1. 文件读取逻辑错误:使用line.read()一次性读取全部内容,导致正则匹配把所有数字混在一起,无法对应每组时间和温度数据。
  2. 未区分时间行与温度行:没有识别HH:MM:SS格式的时间行,直接提取所有数字,数据对应关系混乱。
  3. 缺少时间转datetime的处理:仅提取时分秒数值,未转换为可用于绘图的datetime对象。
  4. 无绘图逻辑:读取数据后未实现温度随时间变化的可视化。

修正后的完整代码

import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter
from datetime import datetime, date
import re

def main():
    file_path = r"C:\Users\sarad\ss1.dat.log"
    # 初始化数据存储列表
    timestamps = []
    # 假设s1-s8对应8个测温点的温度数据
    temps = {
        "s1": [], "s2": [], "s3": [], "s4": [],
        "s5": [], "s6": [], "s7": [], "s8": []
    }

    with open(file_path, 'r') as f:
        lines = f.readlines()
        i = 0
        total_lines = len(lines)
        while i < total_lines:
            current_line = lines[i].strip()
            # 匹配时分秒格式的时间行(如00:00:08)
            time_match = re.match(r'^(\d{2}):(\d{2}):(\d{2})$', current_line)
            if time_match:
                # 提取时分秒
                h, m, s = map(int, time_match.groups())
                # 结合当前日期生成datetime对象(如果日志有日期,可替换为日志中的日期)
                current_date = date.today()
                timestamp = datetime(current_date.year, current_date.month, current_date.day, h, m, s)
                timestamps.append(timestamp)
                # 移动到下一行,读取温度数据
                i += 1
                # 读取温度行(假设时间行后紧跟一行包含8个温度值,根据实际格式调整)
                if i < total_lines:
                    temp_line = lines[i].strip()
                    # 提取所有浮点数字
                    temp_values = re.findall(r'\d+\.?\d*', temp_line)
                    if len(temp_values) == 8:
                        # 将温度值对应存入各列表
                        temps["s1"].append(float(temp_values[0]))
                        temps["s2"].append(float(temp_values[1]))
                        temps["s3"].append(float(temp_values[2]))
                        temps["s4"].append(float(temp_values[3]))
                        temps["s5"].append(float(temp_values[4]))
                        temps["s6"].append(float(temp_values[5]))
                        temps["s7"].append(float(temp_values[6]))
                        temps["s8"].append(float(temp_values[7]))
            i += 1

    # 绘制温度随时间变化的图表
    plt.figure(figsize=(12, 6))
    # 遍历每个测温点绘图
    colors = plt.cm.viridis_r(range(8))
    for idx, (name, temp_list) in enumerate(temps.items()):
        if len(temp_list) == len(timestamps):
            plt.plot(timestamps, temp_list, label=name, color=colors[idx], linewidth=1.5)

    # 设置图表格式
    plt.gcf().autofmt_xdate()
    date_format = DateFormatter('%H:%M:%S')
    plt.gca().xaxis.set_major_formatter(date_format)
    plt.xlabel('时间')
    plt.ylabel('温度')
    plt.title('各测温点温度随时间变化曲线')
    plt.legend(loc='upper right')
    plt.grid(True, linestyle='--', alpha=0.7)
    plt.tight_layout()
    plt.show()

if __name__ == "__main__":
    main()

关键改进说明

  • 按行分组解析:逐行读取文件,先识别HH:MM:SS格式的时间行,再读取后续的温度数据行,确保每组时间对应一组温度值。
  • 时间转换:将时分秒结合当前日期转换为datetime对象,满足matplotlib绘图对时间格式的要求。
  • 灵活的温度读取:用正则提取温度行中的所有浮点数值,适配不同的温度行格式(只要一行包含8个数值即可,若温度分多行,可调整循环逻辑)。
  • 完整绘图逻辑:使用matplotlib绘制多曲线图表,添加坐标轴标签、图例、网格等,提升可视化效果。

注意事项

如果温度数据不是紧跟时间行的一行,而是多行(比如每个section占一行),需要调整代码中的温度读取逻辑,例如:在匹配到时间行后,连续读取对应行数的温度数据,再合并到s1-s8列表中(根据实际数据结构调整)。

内容的提问来源于stack exchange,提问作者Saradindu Samanta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 09:13:30