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

相关推荐
酷爱码1 小时前
如何通过python连接hive,并对里面的表进行增删改查操作
开发语言·hive·python
蹦蹦跳跳真可爱5891 小时前
Python----深度学习(基于深度学习Pytroch簇分类,圆环分类,月牙分类)
人工智能·pytorch·python·深度学习·分类
MinggeQingchun4 小时前
Python - 爬虫-网页解析数据-库lxml(支持XPath)
爬虫·python·xpath·lxml
Python自动化办公社区5 小时前
Python 3.14:探索新版本的魅力与革新
开发语言·python
weixin_贾6 小时前
最新AI-Python机器学习与深度学习技术在植被参数反演中的核心技术应用
python·机器学习·植被参数·遥感反演
张槊哲6 小时前
函数的定义与使用(python)
开发语言·python
船长@Quant6 小时前
文档构建:Sphinx全面使用指南 — 实战篇
python·markdown·sphinx·文档构建
偶尔微微一笑7 小时前
AI网络渗透kali应用(gptshell)
linux·人工智能·python·自然语言处理·编辑器
船长@Quant8 小时前
文档构建:Sphinx全面使用指南 — 基础篇
python·markdown·sphinx·文档构建
喵手9 小时前
从 Java 到 Kotlin:在现有项目中迁移的最佳实践!
java·python·kotlin