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_()

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

# 导远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_()

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值