python-根据关键词匹配连续的内容

运用PyQt5生成可执行小程序:匹配起始关键词到截止关键词区间的GGA格式的内容,支持多选文件,并清除过程中产生的复制文件。

GGA文件如下:

$GPZDA,063052.00,16,10,2023,,*61
$GPGGA,063052.00,4349.7377413,N,12509.8354912,E,4,40,0.6,222.928,M,0.00,M,01,2445*69
$GPZDA,063053.00,16,10,2023,,*60
$GPGGA,063053.00,4349.7377412,N,12509.8354914,E,4,40,0.6,222.926,M,0.00,M,01,2445*61
$GPZDA,063054.00,16,10,2023,,*67

小程序界面:

python-根据关键词匹配连续的内容_第1张图片

运行pyinstaller -F -w setup.py -n Pytext命令,生成可执行程序:
import shutil
import re
import datetime
import os

from PyQt5.QtWidgets import QApplication, QDialog, QVBoxLayout, QLabel, QLineEdit, QPushButton, QFileDialog


class MyDialog(QDialog):
    def __init__(self, parent=None):
        super(MyDialog, self).__init__(parent)
        self.setWindowTitle('提取GGA文件:复制-匹配-裁剪')
        self.setGeometry(100, 100, 500, 300)

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

        # 创建两个文本输入框
        label1 = QLabel('请输入起始关键字:如时分秒063055,或者063053.00,16,10,2023', self)
        layout.addWidget(label1)
        self.text_input1 = QLineEdit(self)
        self.text_input1.setText("063053.00,16,10,2023")
        layout.addWidget(self.text_input1)

        label2 = QLabel('请输入截止关键字:', self)
        layout.addWidget(label2)
        self.text_input2 = QLineEdit(self)
        self.text_input2.setText("070434.00,16,10,2023")
        layout.addWidget(self.text_input2)

        # 创建两个文件选择框
        label3 = QLabel('请选择GGA原文件:可以多选', self)
        layout.addWidget(label3)
        self.file_input1 = QPushButton('浏览...', self)
        layout.addWidget(self.file_input1)
        self.file_input1.clicked.connect(self.open_file_dialog1)

        label4 = QLabel('请选择保存文件的目录:', self)
        layout.addWidget(label4)
        self.file_input2 = QPushButton('浏览...', self)
        layout.addWidget(self.file_input2)
        self.file_input2.clicked.connect(self.open_file_dialog2)

        # 添加确认执行按钮
        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()
            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 open_file_dialog2(self):
        # 打开第二个文件选择对话框
        options = QFileDialog.Options()
        options |= QFileDialog.ReadOnly
        path2 = QFileDialog.getExistingDirectory(self, '选择存放的目录', '.')
        if path2:
            self.file_input2.setText(path2)

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

        now = datetime.datetime.now()
        if ("PROD" in src_path) and ("NRTK" in src_path):
            file_name = "PROD_NRTK_" + now.strftime('%Y%m%d_%H%M%S')
        elif ("TEST" in src_path) and ("NRTK" in src_path):
            file_name = "TEST_NRTK_" + now.strftime('%Y%m%d_%H%M%S')
        elif "PROD" in src_path:
            file_name = "PROD_" + now.strftime('%Y%m%d_%H%M%S')
        elif "TEST" in src_path:
            file_name = "TEST_" + now.strftime('%Y%m%d_%H%M%S')
        else:
            print("非PROD和TEST环境的NRTK和SSR2OSR文件")
            file_name = now.strftime('%Y%m%d_%H%M%S')

        shutil.copy2(src_path, dst_path + '/' + file_name)

        dst_w_path = dst_path + '/' + file_name + 'D'
        with open(dst_path + '/' + file_name, 'r') as dst, open(dst_w_path, 'w') as dst_w:
            # 默认不写入文件
            writing = False
            num_count = 0
            for line in dst:
                # 正则匹配,起始行
                if re.search(pattern_start, line) and line.startswith('$GPZDA'):
                    writing = True
                if writing:
                    num_count += 1
                    dst_w.write(line)
                # 正则匹配,截止行
                if re.search(pattern_end, line):  # and line.startswith('$GPGGA'):
                    writing = False
                    break
            print(r'总共%s行写入完成,起始于:%s,截止于:%s' % (num_count, pattern_start, pattern_end))

        if 'merged' in src_path:
            os.remove(src_path)
            os.remove(dst_path + '/' + file_name)
        else:
            os.remove(dst_path + '/' + file_name)


if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)
    dialog = MyDialog()
    dialog.exec_()

你可能感兴趣的:(python,开发语言)