提取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

相关推荐
Geoking.14 小时前
NumPy zeros() 函数详解
python·numpy
Full Stack Developme14 小时前
java.text 包详解
java·开发语言·python
丁浩66615 小时前
Python机器学习---2.算法:逻辑回归
python·算法·机器学习
B站_计算机毕业设计之家15 小时前
计算机毕业设计:Python农业数据可视化分析系统 气象数据 农业生产 粮食数据 播种数据 爬虫 Django框架 天气数据 降水量(源码+文档)✅
大数据·爬虫·python·机器学习·信息可视化·课程设计·农业
Q_Q51100828515 小时前
python+uniapp基于微信小程序的旅游信息系统
spring boot·python·微信小程序·django·flask·uni-app·node.js
鄃鳕15 小时前
python迭代器解包【python】
开发语言·python
懷淰メ16 小时前
python3GUI--模仿百度网盘的本地文件管理器 By:PyQt5(详细分享)
开发语言·python·pyqt·文件管理·百度云·百度网盘·ui设计
Q_Q51100828516 小时前
python基于web的汽车班车车票管理系统/火车票预订系统/高铁预定系统 可在线选座
spring boot·python·django·flask·node.js·汽车·php
新子y16 小时前
【小白笔记】普通二叉树(General Binary Tree)和二叉搜索树的最近公共祖先(LCA)
开发语言·笔记·python
囚生CY16 小时前
【速写】优化的深度与广度(Adam & Moun)
人工智能·python·算法