提取log文件中的数据,画图

  1. 要提取的log格式如下:

  1. 代码如下:

python 复制代码
import re

import matplotlib.pyplot as plt
import numpy as np

import argparse
from os import path
from re import search


class DataExtractor(object):
    ''' DataExtrator class '''

    def __init__(self, infile, keyword, outfile):
        '''
        构造函数

        infile:输入文件名
        keyword:目标数据前面的关键字
        outfile:输出文件名
        '''

        self.infile = infile
        self.keyword = keyword
        self.outfile = outfile

    def data_after_keyword(self):
        ''' Extract data from infile after the keyword. '''

        try:
            data = []
            patt = '%s:\s*(\d+\.?\d+)' % self.keyword  # 使用正则表达式搜索数据,关键字冒号,有空格或者没有空格,  小数点前后的数字
            with open(self.infile, 'r') as fi:
                with open(self.outfile, 'w') as fo:
                    for eachLine in fi:
                        s = search(patt, eachLine)
                        if s is not None:
                            fo.write(s.group(1) + '\n')
                            data.append(float(s.group(1)))
            return data
        except IOError:
            print(
                "Open file [%s] or [%s] failed!" % (self.infile, self.outfile))
            return False


if __name__ == "__main__":

    names = ['train loss', 'train psnr', 'iter_time', 'data_time', 'epoch time']
    file = r'D:\512_bs4_20230922_182434.log'
    fileout = file[:-4] + '_out.log'

    dd = dict()
    for name in names:
        extractor = DataExtractor(file, name, fileout)
        dd[name] = extractor.data_after_keyword()
    print(dd)

    x = range(len(dd[names[0]]))
    plt.figure()
    plt.subplot(131)
    plt.plot(x, dd[names[0]], 'r')
    plt.subplot(132)
    plt.plot(x, dd[names[1]], 'r')
    plt.subplot(133)
    plt.plot(x, dd[names[2]], 'g', x, dd[names[3]], 'b')
    plt.show()
  1. 得到结果

参考:

https://blog.csdn.net/guo_qingxia/article/details/113979135

https://blog.csdn.net/letian3658/article/details/105882965

相关推荐
vortex515 分钟前
Villain:新一代轻量级 C2 框架完整使用指南
python·网络安全·kali·c2
测试员周周18 分钟前
【AI测试系统】第5篇:AI 编码工具抛硬币?我们用 LangGraph 做了个“确定性+AI”的测试系统(附自愈架构)
人工智能·python·功能测试·测试工具·架构·langchain·单元测试
Levin__NLP_CV_AIGC20 分钟前
py文件中文件复制方法
开发语言·python
庚昀◟25 分钟前
腾讯云 CVM + Docker + Jenkins + GitLab CI/CD 全流程指南(python、flask实现简单计算器)
python·ci/cd·docker·flask·jenkins
H_unique25 分钟前
LangChain:创建工具Ⅰ
python·langchain
eqwaak034 分钟前
PyTorch张量操作全攻略:从入门到精通
开发语言·人工智能·pytorch·python
A懿轩A37 分钟前
Ghostty:告别 Mac 毛坯终端,打造 2026 最丝滑的 Ghostty AI 开发驾驶舱——Claude Code 团队也在用
python·macos·策略模式
Chasing Aurora38 分钟前
python 安装依赖和导入模块 详解
开发语言·python·虚拟环境·import·pyenv·requirements
念恒1230642 分钟前
Python(for循环)
python·学习
咱那飘逸的长发43 分钟前
Trae java项目配置全局maven和jdk
java·python·maven