基于tkinter
库的Python GUI(图形用户界面)应用程序,选择一个文本或CSV文件,并对该文件中的特定格式数据进行清洗和转换,然后将清洗后的数据保存到一个新的文本文件中
import tkinter as tk # 导入tkinter库用于创建GUI界面
from tkinter import filedialog, Button, Entry, messagebox # 从tkinter导入文件对话框、按钮、输入框和消息框组件
import re # 导入正则表达式库用于文本匹配
import os # 导入os库用于文件路径操作
# 定义选择文件的函数
def select_file(file_path_entry):
# 打开文件选择对话框,让用户选择一个文本或CSV文件
file_path = filedialog.askopenfilename(title="Select a text file", filetypes=[("Text files", "*.txt"), ("CSV files", "*.csv"), ("All files", "*.*")])
if file_path: # 如果用户选择了文件
file_path_entry.config(state=tk.NORMAL) # 将输入框设置为可编辑状态
file_path_entry.delete(0, tk.END) # 清空输入框
file_path_entry.insert(0, file_path) # 将选择的文件路径插入到输入框中
file_path_entry.config(state='readonly') # 将输入框设置为只读状态
# 定义转换文本的函数
def transform_text(file_path_entry):
# 从输入框中获取文件路径
file_path = file_path_entry.get()
if not file_path: # 如果文件路径为空
messagebox.showinfo("Information", "No file selected or file path is empty.") # 显示信息框提示用户
return
# 数据清洗逻辑
start_cleaning = False # 标记是否开始清洗数据
cleaned_data = [] # 存储清洗后的数据
with open(file_path, 'r') as file: # 打开文件
for line in file: # 逐行读取文件
if 'ceshi_flag=01 ok' in line: # 如果找到特定标记,开始清洗数据
start_cleaning = True
continue
if start_cleaning: # 如果已经开始清洗数据
matches = re.findall(r'\[\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}\]\s*(.+)', line) # 使用正则表达式匹配特定格式的数据
for match in matches:
data_points = match.split(',') # 将匹配到的数据按逗号分割
for dp in data_points:
num = re.findall(r'-?\d+\.\d+|-?\d+', dp) # 使用正则表达式提取数字
if num:
cleaned_data.extend(num) # 将提取到的数字添加到清洗后的数据列表中
# 构造输出文件路径,将清洗后的数据保存到新的文本文件中
output_file_path = os.path.splitext(file_path)[0] + "_cleaned.txt"
with open(output_file_path, 'w') as out_file:
for data_point in cleaned_data:
out_file.write(f"{data_point}\n") # 每个数据点占一行
# 显示成功信息框,提示用户数据转换完成
messagebox.showinfo("Success", f"Data transformation completed.\nCleaned data saved to {output_file_path}")
# 创建UI界面
root = tk.Tk() # 初始化tkinter窗口
root.title("Data Transformer") # 设置窗口标题
# 创建文本框显示文件路径
file_path_entry = Entry(root, width=50, state='readonly') # 创建一个只读输入框用于显示文件路径
file_path_entry.pack() # 将输入框添加到窗口中
# 创建选择文件按钮
choose_file_button = Button(root, text="Choose File", command=lambda: select_file(file_path_entry)) # 创建一个按钮,点击时调用select_file函数
choose_file_button.pack() # 将按钮添加到窗口中
# 创建转换文本按钮,放在下方
transform_button = Button(root, text="Transform Text", command=lambda: transform_text(file_path_entry)) # 创建一个按钮,点击时调用transform_text函数
transform_button.pack() # 将按钮添加到窗口中
# 运行主循环,保持窗口显示
root.mainloop()