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

小程序界面:

复制代码
运行pyinstaller -F -w setup.py -n Pytext命令,生成可执行程序:
python 复制代码
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_()
相关推荐
C_心欲无痕5 分钟前
Next.js 的服务端路由:对应api文件夹
开发语言·javascript·ecmascript
zh_xuan17 分钟前
kotlin 类委托
开发语言·kotlin
墨雨晨曦8832 分钟前
2026/01/20 java总结
java·开发语言
52Hz11839 分钟前
二叉树理论、力扣94.二叉树的中序遍历、104.二叉树的最大深度、226.反转二叉树、101.对称二叉树
python·算法·leetcode
look ahead to41 分钟前
关于PYQT qt designer的网格布局 单控件占多行的处理
开发语言·qt·pyqt
王德博客41 分钟前
【C++继承】笔试易错题目
开发语言·c++·继承
卖个几把萌44 分钟前
解决 Python 项目依赖冲突:使用 pip-tools 一键生成现代化的 requirements.txt
开发语言·python·pip
黎雁·泠崖1 小时前
Java字符串入门:API入门+String类核心
java·开发语言·python
哈哈不让取名字1 小时前
用Pygame开发你的第一个小游戏
jvm·数据库·python
程序员敲代码吗1 小时前
Python异步编程入门:Asyncio库的使用
jvm·数据库·python