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_()
相关推荐
时光追逐者1 小时前
C#拾遗补漏之 Dictionary 详解
开发语言·c#·.net·.net core
java1234_小锋1 小时前
【NLP舆情分析】基于python微博舆情分析可视化系统(flask+pandas+echarts) 视频教程 - 微博舆情数据可视化分析-热词情感趋势树形图
python·信息可视化·自然语言处理
夏影孤灯2 小时前
C 语言问题
c语言·开发语言
宸津-代码粉碎机2 小时前
LLM 模型部署难题的技术突破:从轻量化到分布式推理的全栈解决方案
java·大数据·人工智能·分布式·python
都叫我大帅哥2 小时前
当数据流经LangChain时,RunnablePassthrough如何成为“最懒却最聪明”的快递员?
python·langchain
都叫我大帅哥2 小时前
机器学习界的“钢铁侠”:支持向量机(SVM)全方位指南
python·机器学习
柴 基5 小时前
Jupyter Notebook 使用指南
ide·python·jupyter
新手小新6 小时前
C++游戏开发(2)
开发语言·前端·c++
Python×CATIA工业智造6 小时前
Pycaita二次开发基础代码解析:几何体重命名与参数提取技术
python·pycharm·pycatia
你的电影很有趣7 小时前
lesson30:Python迭代三剑客:可迭代对象、迭代器与生成器深度解析
开发语言·python