python 多关键字筛选日志文件内容

前言

直接上源码,注释齐全,一看就懂。
在这里插入图片描述


一、使用步骤

1.引入库

代码如下(示例):

import os
import re
import time
from datetime import datetime
from tkinter import *
from tkinter.filedialog import *
from tkinter.scrolledtext import ScrolledText
from tkinter import messagebox

2.主代码

代码如下(示例):


def extract_logs_with_keywords():
    if not os.path.exists('./data'):
        os.makedirs('./data')
    txt.delete("1.0", "end")  # 清空内容
    log_file = upload_text_var.get()
    if log_file == '':
        messagebox.showerror('提示', '请选择需要提取的文本')
        return False
    if not os.path.exists(log_file):
        messagebox.showerror('提示', '选择的文本不存在')
        return False
    keywords = keyword_text_var.get()
    keywords = eval(keywords)  # 传过来变字符串了,重新处理成list
    # print(type(eval(keywords)))
    pattern = '.*?'.join(keywords)  # 使用关键词生成正则表达式
    # print(pattern)
    pattern = f'({pattern})'  # 将多个关键词组合在一起为一个组
    compiled_pattern = re.compile(pattern)

    matched_lines = []
    with open(log_file, 'r', encoding='utf-8') as file:
        for line in file:
            matches = compiled_pattern.search(line)  # 只拿到第一个结果就返回
            if matches:
                matched_lines.append(line.strip())
                # 执行数据插入
                tit = str(line) + '\n\n'
                txt.insert(END, tit)  # 插入最后一行
                txt.see(END)  # 跳转到最后一行
                txt.update()  # 实时显示文本框内容
    # return matched_lines
    # for line in matched_lines:
    #     print(line)
    length = len(matched_lines)
    tip_text_var.set('共提取数据:    ' + str(length) + '    条')
    if length == 0:
        messagebox.showinfo('提示', '暂未查找到相关数据!')
        return False
    # 将数据写入文本
    file_name = os.path.basename(upload_text_var.get())
    output_file = f'./data/{file_name}  {get_now_date()}.txt'
    with open(output_file, 'w', encoding='utf-8') as file:
        for item in matched_lines:
            file.write(f"{item}\n\n")


def upload_file():
    # 读取图片打开图片
    filetypes = (
        # ('All files', '*'),
        ('文本文件', '.txt'),
        ('文本文件', '.log'),
    )
    # filename = askopenfilename(initialdir="/",title='选择一个文本文件', filetypes=filetypes)
    filename = askopenfilename(title='选择一个文本文件', filetypes=filetypes)

    # 显示图片路径
    upload_text_var.set(filename)


# 打开特定目录
def open_directory():
    current_folder = os.getcwd()  # 获取当前文件夹(作为默认文件夹)
    current_folder = f"{current_folder}\\data"
    save_file_directory = current_folder  # 文件保存目录 (如果不存在则使用默认目录)
    if not os.path.exists(save_file_directory):
        os.makedirs(save_file_directory)
    save_dir = os.path.dirname(f"{save_file_directory}/")
    print(save_dir)
    os.system('start ' + save_dir)


# 获取当前时间(文件名不能包含><:(冒号)等特殊符号)
def get_now_date():
    # 获取当前日期和时间
    now = datetime.now()
    date_time_str = now.strftime("%Y-%m-%d %H.%M.%S")
    return date_time_str

3.tkinter部分

代码如下(示例):

root = Tk()
root.title('日志多关键字提取')
root.state("zoomed")  # 窗口最大化 ”zoomed”这个参数只能在windowns下使用

frame = Frame(root, padx=10, pady=10)
frame.pack(fill='both', expand=True)
upload_file_button = Button(frame, text='选择文本', command=upload_file)
upload_file_button.grid(row=0, column=0)
# 创建一个StringVar对象,用于显示文件路径
upload_text_var = StringVar()
upload_text_var.set("")
upload_file_entry = Entry(frame, textvariable=upload_text_var)
upload_file_entry.grid(row=0, column=1, sticky=E + W, ipady=4, padx=5)
frame.grid_columnconfigure(1, weight=1)  # 第一列权重设为1
# 提示
tip_button = Label(frame, text="关键字必须为以下格式['2024/08/15', 'error','***','**']或['2024/08/15']", font=("微软雅黑", 10), fg='red')
tip_button.grid(row=1, column=1)

keyword_button = Label(frame, text='关键字')
keyword_button.grid(row=2, column=0)
keyword_text_var = StringVar()
keyword_text_var.set("['2024/08/15', 'error']")
keyword_entry = Entry(frame, textvariable=keyword_text_var, font=('Size', 20))
keyword_entry.grid(row=2, column=1, sticky=E + W, ipady=4, padx=5)

start_button = Button(frame, text='开始提取', command=extract_logs_with_keywords)
start_button.grid(row=3, column=0, columnspan=2, padx=(0, 180), pady=10, ipadx=5)
open_button = Button(frame, text='打开目录', command=open_directory)
open_button.grid(row=3, column=0, columnspan=2, padx=(150, 0), ipadx=5)

# 滚动文本
txt = ScrolledText(frame)
txt.grid(row=4, column=0, columnspan=2, sticky=W + E + N + S)
frame.grid_rowconfigure(4, weight=1)

tip_text_var = StringVar()
tip_text_var.set("")
tip_label = Label(frame, textvariable=tip_text_var, fg='red')
tip_label.grid(row=5, column=0, columnspan=2)

root.mainloop()


总结

提示:这里对文章进行总结:

直接运行就可以使用

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值