python 按时间戳删除32×32数组的前2列和后9列(包含批量处理多个txt)之后删除后6行
雨滴谱仪选择,行为速度,列为尺度
那么我只留下我需要的d列数据,删除不需要的列:
# -*- coding:utf-8 -*- """ @author: suyue @file: deletlie.py @time: 2024/05/01 @desc: """ import numpy as np import pandas as pd file_path = '/NM004-20230627224400-20230627224859-0.txt' # 读整个txt文件读取到单个字符串 with open(file_path, 'r', errors='ignore') as file: file_content = file.read() # 按时间戳拆分内容以查找单独的部分 # 时间戳的格式为 YYYY-MM-DD HH:MM:SS,因此我们将使用正则表达式根据此模式进行拆分 import re sections = re.split(r'\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\n', file_content) # print(sections) date = [x for x in file_content.split('\n') if len(x) == 19] # 如果txt第一个元素为空值(由于拆分),则将其删除 if not sections[0]: sections.pop(0) final_data = {} for i in range(len(sections)): final_data[date[i]] = sections[i] # 删除不要的列数 df_final_values = [] for key, value in final_data.items(): lines = value.strip().split('\n') matrix = [line.split() for line in lines] df = pd.DataFrame(matrix) # 删除前2列 df.drop(df.columns[:2], axis=1, inplace=True) # 删除后9列 df.drop(df.columns[-9:], axis=1, inplace=True) df_final_values.append(df.values.tolist())
# 将结果写入txt,采用追加写入的方式 index = 0 with open('/output.txt', 'w', errors='ignore') as file: for key, _ in final_data.items(): file.write(key + '\n') for df_values in df_final_values[index]: file.write('\t'.join(df_values) + '\n') index += 1 file.write('\n')
得到:
整理一下这个代码,用def来定义,也可以得到同样的效果:
import numpy as np import re def process_file(input_file, output_file): # 用于匹配时间戳的正则表达式(这里需要根据你的时间戳格式进行修改) timestamp_pattern = re.compile(r'^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$') current_array = [] timestamp = None results = [] with open(input_file, 'r') as f: for line in f: line = line.strip() # 检查是否是时间戳 if timestamp_pattern.match(line): # 如果当前数组不为空,说明我们完成了一个部分的读取 if current_array: # 将当前数组转换为numpy数组,并删除前2列和后9列 array = np.array(current_array, dtype=int) # 假设数据是浮点数 processed_array = array[:, 2:-9] # 删除前2列和后9列 # 如果没有超出边界,则保存结果 if processed_array.shape[1] > 0: results.append((timestamp, processed_array)) # 更新时间戳和当前数组 timestamp = line current_array = [] else: # 如果不是时间戳,则假设是数组数据(需要根据实际情况调整) # 这里假设数据是用空格分隔的浮点数 if line: # 避免处理空行 row = list(map(int, line.split())) current_array.append(row) # 检查最后一个数组(如果有的话) if current_array: array = np.array(current_array, dtype=int) processed_array = array[:, 2:-9] if processed_array.shape[1] > 0: results.append((timestamp, processed_array)) # 将结果保存到输出文件 with open(output_file, 'w') as out_f: for ts, array in results: # 写入时间戳(可以根据需要调整格式) out_f.write(f"{ts}\n") # 写入处理后的数组数据 for row in array: out_f.write(" ".join(map(str, row)) + "\n") out_f.write("\n") # 每个部分之间用空行分隔 # 使用示例 input_file = 'D:/rain/53464-20230627202000-20230627202159-0.txt' output_file = 'D:/rain/53464-20230627202000-20230627202159-1.txt' process_file(input_file, output_file)
批量处理多个txt:
import os import re def process_array_data(data_lines): """ 处理数组数据,删除前2列和后9列。 """ processed_data = [] for line in data_lines: # 分割每行的数字,转换为整数列表,并删除前2个和后9个元素 numbers = list(map(int, line.strip().split())) processed_row = numbers[2:-9] processed_data.append(processed_row) return processed_data def process_single_file(file_path): """ 处理单个TXT文件,返回处理后的内容(时间戳和对应的处理后的数组)。 """ with open(file_path, 'r', encoding='utf-8') as file: lines = file.readlines() results = [] i = 0 while i < len(lines): # 匹配时间戳 timestamp_match = re.match(r'\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$', lines[i].strip()) if timestamp_match: timestamp = lines[i].strip() i += 1 # 跳过空行 # 读取接下来的32行数据 array_lines = lines[i:i + 32] processed_array = process_array_data(array_lines) # 将处理后的数组和时间戳添加到结果列表中 results.append((timestamp, processed_array)) # 移动到下一个时间戳(如果有的话) i += 32 else: i += 1 # 如果不匹配时间戳,则继续检查下一行 return results def process_txt_files_in_directory(input_dir, output_dir): """ 批量处理指定目录中的所有.txt文件,并将结果保存到输出文件夹中的新TXT文件中。 """ if not os.path.exists(output_dir): os.makedirs(output_dir) for filename in os.listdir(input_dir): if filename.endswith(".txt"): input_file_path = os.path.join(input_dir, filename) results = process_single_file(input_file_path) # 获取处理后的结果 # 构造输出文件的名称和路径 output_filename = os.path.splitext(filename)[0] + '_processed.txt' output_file_path = os.path.join(output_dir, output_filename) # 将处理后的内容写入新的TXT文件 with open(output_file_path, 'w', encoding='utf-8') as output_file: first_timestamp = True # 标记是否为第一个时间戳 for timestamp, array in results: # 如果不是第一个时间戳,则写入一个空行 if not first_timestamp: output_file.write("\n") first_timestamp = False # 更新标记 # 写入时间戳 output_file.write(f"{timestamp}\n") # 写入处理后的数组数据 for row in array: output_file.write(" ".join(map(str, row)) + "\n") # 示例使用 input_directory = 'F:/rain' output_directory = 'F:/rain/result' process_txt_files_in_directory(input_directory, output_directory)
得到个数组之后,删除数组的后6行:
#!usr/bin/env python # -*- coding:utf-8 -*- """ @author: Suyue @file: lianxi2.py @time: 2025/02/10 @desc:删除速度后6行 """ import os import re def process_array_data(data_lines): """ 处理数组数据,删除后6行。 """ processed_data = [] for line in data_lines: # 分割每行的数字,转换为整数列表 numbers = list(map(float, line.strip().split())) processed_data.append(numbers) # 保留整行数据 # 删除后6行 processed_data = processed_data[:-6] return processed_data def process_single_file(file_path): """ 处理单个TXT文件,返回处理后的内容(时间戳和对应的处理后的数组)。 """ with open(file_path, 'r', encoding='utf-8') as file: lines = file.readlines() results = [] i = 0 while i < len(lines): # 匹配时间戳 timestamp_match = re.match(r'\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$', lines[i].strip()) if timestamp_match: timestamp = lines[i].strip() i += 1 # 跳过空行 # 读取接下来的32行数据 array_lines = lines[i:i + 32] processed_array = process_array_data(array_lines) # 将处理后的数组和时间戳添加到结果列表中 results.append((timestamp, processed_array)) # 移动到下一个时间戳(如果有的话) i += 32 else: i += 1 # 如果不匹配时间戳,则继续检查下一行 return results def process_txt_files_in_directory(input_dir, output_dir): """ 批量处理指定目录中的所有.txt文件,并将结果保存到输出文件夹中的新TXT文件中。 """ if not os.path.exists(output_dir): os.makedirs(output_dir) for filename in os.listdir(input_dir): if filename.endswith(".txt"): input_file_path = os.path.join(input_dir, filename) results = process_single_file(input_file_path) # 获取处理后的结果 # 构造输出文件的名称和路径 output_filename = os.path.splitext(filename)[0] + '_processed.txt' output_file_path = os.path.join(output_dir, output_filename) # 将处理后的内容写入新的TXT文件 with open(output_file_path, 'w', encoding='utf-8') as output_file: first_timestamp = True # 标记是否为第一个时间戳 for timestamp, array in results: # 如果不是第一个时间戳,则写入一个空行 if not first_timestamp: output_file.write("\n") first_timestamp = False # 更新标记 # 写入时间戳 output_file.write(f"{timestamp}\n") # 写入处理后的数组数据 for row in array: output_file.write(" ".join(map(str, row)) + "\n") # 示例使用 input_directory = 'F:/snow_N' output_directory = 'F:/result' process_txt_files_in_directory(input_directory, output_directory)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了