python_根据关键词匹配文件中的数据并绘图

根据关键词匹配文件中特定的数值,然后绘制曲线图;

python 复制代码
# 导远los数据的eph & ssr & los num曲线
import os
import matplotlib.pyplot as plt
import re
from PyQt5.QtWidgets import QApplication, QDialog, QVBoxLayout, QLabel, QLineEdit, QPushButton, QFileDialog

plt.rcParams["font.sans-serif"] = ["SimHei"]  # 设置显示中文字体
plt.rcParams["axes.unicode_minus"] = False  # 设置正常显示符号


# os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
# os.environ["CUDA_VISIBLE_DEVICES"] = "1"

class MyDialog(QDialog):
    def __init__(self, parent=None):
        super(MyDialog, self).__init__(parent)
        self.setWindowTitle('nLos_绘图工具')
        self.setGeometry(100, 100, 200, 200)

        # 创建垂直布局管理器
        layout = QVBoxLayout()

        # 创建文件选择框
        label3 = QLabel('请点击浏览按钮,选择nLos的log文件;\n再点击执行按钮,绘制曲线。', self)
        layout.addWidget(label3)
        self.file_input1 = QPushButton('浏览...', self)
        layout.addWidget(self.file_input1)
        self.file_input1.clicked.connect(self.open_file_dialog1)

        # 添加确认执行按钮
        self.ok_button = QPushButton('执行', self)
        self.ok_button.clicked.connect(self.execute)
        layout.addWidget(self.ok_button)

        # 将布局设置为主窗口的布局
        self.setLayout(layout)

    def open_file_dialog1(self):
        file_dialog = QFileDialog(self)
        file_dialog.setFileMode(QFileDialog.ExistingFiles)
        if file_dialog.exec_():
            file_paths = file_dialog.selectedFiles()
            merged_filename = ""
            if len(file_paths) > 1:
                # 获取第一个文件的目录和文件名,用于创建合并后的文件名
                directory = os.path.dirname(file_paths[0])
                filename = os.path.splitext(os.path.basename(file_paths[0]))[0]
                merged_filename = os.path.join(directory, f'{filename}_merged').replace('\\', '/')
                with open(merged_filename, 'w') as merged_file:
                    for path in file_paths:
                        with open(path, 'r') as file:
                            merged_file.write(file.read())
                            merged_file.write('\n')  # 在每个文件之间添加换行符
            elif len(file_paths) == 1:
                merged_filename = file_paths
            else:
                print('Please select files.')

            if merged_filename:
                self.file_input1.setText(''.join(merged_filename))

    def execute(self):
        # 执行操作,可以在这里处理输入框和文件选择框的内容
        file_path_s = self.file_input1.text()

        # 匹配的关键字
        keyword_s = 'start time'
        keyword_i = 'input.time'
        keyword_e = 'eph num'
        keyword_d = 'dpi_sdk ssr num'
        keyword_l = 'nLos'

        with open(file_path_s, 'r', encoding="utf-8", errors="ignore") as file:
            lines = file.readlines()
            it_list, en_list, dn_list, ln_list = [], [], [], []
            it = 0
            for index, line in enumerate(lines):
                # 匹配相近的两行关键词
                if line.startswith(keyword_e) and lines[index + 1].startswith(keyword_d):
                    # 空格分隔,去掉末尾的换行
                    en = line.split(' ')[-1].strip('\n')
                    dn = lines[index + 1].split(' ')[-1].strip('\n')
                    # 解决绘图时,y轴排序错乱问题,字符转换成整型
                    en_list.append(int(en))
                    dn_list.append(int(dn))
                # 匹配nLos关键词
                if keyword_l in line:
                    # 空格分隔,去掉末尾的换行
                    ln = re.split("[,| |:|=]+", line)[4]
                    # print(ln)
                    it = re.split("[,| |:|=]+", line)[-1].strip('\n')
                    # print(it)
                    ln_list.append(int(ln))
                    it_list.append(it)

            # 剔除掉第一个
            # ln_list.pop(0)
            # print(len(ln_list))

            # 添加标签和标题
            plt.xlabel('时间')
            plt.ylabel('数值')
            # plt.title(keyword_e + ' & ' + keyword_d + ' & ' + keyword_l, fontsize=24)
            file_name = os.path.basename(file_path_s)
            plt.title(file_name, fontsize=24)

            # 显示网格线和设置背景色
            plt.grid(True)
            plt.gca().set_facecolor('lightgrey')

            # plt.plot(it_list, en_list, it_list, dn_list)
            # linestyle = "--" 表示虚线,":"表示点虚线,"-."表示点划线,
            plt.plot(it_list, en_list, linestyle='--', label=keyword_e, marker='o')
            plt.plot(it_list, dn_list, linestyle=':', label=keyword_d, marker='v')
            plt.plot(it_list, ln_list, linestyle='-.', label=keyword_l, marker=',')

            # 添加图例
            plt.legend()
            # 显示图表
            plt.show()


if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)
    dialog = MyDialog()
    # 解决子窗口不能操作的问题
    dialog.show()
    dialog.exec_()

文件中的关键词发生变化,调整后:

python 复制代码
# 导远los数据的eph & ssr & los num曲线
import os
import matplotlib.pyplot as plt
from matplotlib.dates import AutoDateLocator
import re
from PyQt5.QtWidgets import QApplication, QDialog, QVBoxLayout, QLabel, QLineEdit, QPushButton, QFileDialog

plt.rcParams["font.sans-serif"] = ["SimHei"]  # 设置显示中文字体
plt.rcParams["axes.unicode_minus"] = False  # 设置正常显示符号


# os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
# os.environ["CUDA_VISIBLE_DEVICES"] = "1"

class MyDialog(QDialog):
    def __init__(self, parent=None):
        super(MyDialog, self).__init__(parent)
        self.setWindowTitle('los绘图工具')
        self.setGeometry(100, 100, 200, 200)

        # 创建垂直布局管理器
        layout = QVBoxLayout()

        # 创建文件选择框
        label3 = QLabel('请点击浏览按钮,选择los的log文件;\n再点击执行按钮,绘制曲线。\n兼容导远V1.2-V1.4版本', self)
        layout.addWidget(label3)
        self.file_input1 = QPushButton('浏览...', self)
        layout.addWidget(self.file_input1)
        self.file_input1.clicked.connect(self.open_file_dialog1)

        # 添加确认执行按钮
        self.ok_button = QPushButton('执行', self)
        self.ok_button.clicked.connect(self.execute)
        layout.addWidget(self.ok_button)

        # 将布局设置为主窗口的布局
        self.setLayout(layout)

    def open_file_dialog1(self):
        file_dialog = QFileDialog(self)
        file_dialog.setFileMode(QFileDialog.ExistingFiles)
        if file_dialog.exec_():
            file_paths = file_dialog.selectedFiles()
            merged_filename = ""
            if len(file_paths) > 1:
                # 获取第一个文件的目录和文件名,用于创建合并后的文件名
                directory = os.path.dirname(file_paths[0])
                filename = os.path.splitext(os.path.basename(file_paths[0]))[0]
                merged_filename = os.path.join(directory, f'{filename}_merged').replace('\\', '/')
                with open(merged_filename, 'w') as merged_file:
                    for path in file_paths:
                        with open(path, 'r') as file:
                            merged_file.write(file.read())
                            merged_file.write('\n')  # 在每个文件之间添加换行符
            elif len(file_paths) == 1:
                merged_filename = file_paths
            else:
                print('Please select files.')

            if merged_filename:
                self.file_input1.setText(''.join(merged_filename))

    def execute(self):
        # 执行操作,可以在这里处理输入框和文件选择框的内容
        file_path_s = self.file_input1.text()

        # 匹配的关键字
        keyword_s = 'start'  # 新旧版本的start与time之间的空格不一致
        keyword_i = 'input.time'
        keyword_e = 'eph num'
        keyword_d = 'dpi_sdk ssr num'
        keyword_l = 'los num'
        keyword_t = 'time'

        with open(file_path_s, 'r', encoding="utf-8", errors="ignore") as file:
            lines = file.readlines()
            it_list, en_list, dn_list, ln_list = [], [], [], []
            it = 0
            for index, line in enumerate(lines):
                # 匹配相近的三行关键词
                if line.startswith(keyword_s) and lines[index + 1].startswith(keyword_e) and lines[
                    index + 2].startswith(keyword_d):
                    # 空格分隔,去掉末尾的换行
                    # it = line.split(' ')[-1].strip('\n')
                    en = lines[index + 1].split(' ')[-1].strip('\n')
                    dn = lines[index + 2].split(' ')[-1].strip('\n')
                    # print(it, en, dn)
                    # it_list.append(it)
                    # 解决绘图时,y轴排序错乱问题,字符转换成整型
                    en_list.append(int(en))
                    dn_list.append(int(dn))
                # 匹配los num关键词
                if keyword_l in line and lines[index + 1].startswith(keyword_t):
                    # 空格分隔,去掉末尾的换行
                    ln = line.split(' ')[-1].strip('\n')
                    ln_list.append(int(ln))
                    it = re.split("[,| ]+", lines[index + 1])[1].strip('\n')
                    it_list.append(it)

            # 剔除掉第一个,数量需要相等,不然报错
            # ln_list.pop(0)
            # print(len(ln_list))

            # print(len(it_list), len(ln_list), len(en_list), len(dn_list))

            # 列表的数量需要相等,不然绘图的时候会报错,切片获取最小长度的列表
            if len(it_list) > len(en_list):
                it_list = it_list[:len(en_list)]
                ln_list = ln_list[:len(en_list)]
            elif len(it_list) < len(en_list):
                en_list = en_list[:len(it_list)]
                dn_list = dn_list[:len(it_list)]

            # 添加标签和标题
            plt.xlabel('GPST时间')
            plt.ylabel('num数值')
            # plt.title(keyword_e + ' & ' + keyword_d + ' & ' + keyword_l, fontsize=24)
            file_name = os.path.basename(file_path_s)
            plt.title(file_name, fontsize=24)

            # 自动调整刻度
            plt.gca().xaxis.set_major_locator(AutoDateLocator())

            # 显示网格线和设置背景色
            plt.grid(True)
            plt.gca().set_facecolor('lightgrey')

            # plt.plot(it_list, en_list, it_list, dn_list)
            # linestyle = "--" 表示虚线,":"表示点虚线,"-."表示点划线,
            plt.plot(it_list, en_list, linestyle='--', alpha=0.5, label=keyword_e, marker='o', linewidth=4)
            plt.plot(it_list, dn_list, linestyle=':', alpha=0.5, label=keyword_d, marker='v', linewidth=1)
            plt.plot(it_list, ln_list, linestyle='-.', label=keyword_l, marker=',')

            # 添加图例
            plt.legend()
            # 显示图表
            plt.show()


if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)
    dialog = MyDialog()
    # 解决子窗口不能操作的问题
    dialog.show()
    dialog.exec_()
相关推荐
不写八个5 分钟前
Python办公自动化教程(005):Word添加段落
开发语言·python·word
HEX9CF9 分钟前
【CTF Web】Pikachu xss之href输出 Writeup(GET请求+反射型XSS+javascript:伪协议绕过)
开发语言·前端·javascript·安全·网络安全·ecmascript·xss
_.Switch22 分钟前
Python机器学习框架介绍和入门案例:Scikit-learn、TensorFlow与Keras、PyTorch
python·机器学习·架构·tensorflow·keras·scikit-learn
赵荏苒34 分钟前
Python小白之Pandas1
开发语言·python
丶Darling.36 分钟前
代码随想录 | Day26 | 二叉树:二叉搜索树中的插入操作&&删除二叉搜索树中的节点&&修剪二叉搜索树
开发语言·数据结构·c++·笔记·学习·算法
人生の三重奏43 分钟前
前端——js补充
开发语言·前端·javascript
平凡的小码农1 小时前
JAVA实现大写金额转小写金额
java·开发语言
一眼万里*e1 小时前
fish-speech语音大模型本地部署
python·flask·大模型
yttandb1 小时前
重生到现代之从零开始的C语言生活》—— 内存的存储
c语言·开发语言·生活
我明天再来学Web渗透1 小时前
【hot100-java】【二叉树的层序遍历】
java·开发语言·数据库·sql·算法·排序算法