os和split提取期望数据并写入txt

本文介绍了一种从文本文件中提取特定格式数据的方法,并通过条件筛选进行数据处理的过程。重点在于如何使用Python处理文本数据,包括错误处理和数据写入。

在提取数据的过程中,可能每一行出现的情况的不同,我们所需的判断条件报错,cant float加以改进。


with open('catalog.txt','r') as f:
    lines = f.readlines()
    label = []
    for line in lines:
        try:
            x = float(line.split('|')[17])
        except ValueError:
            x = 10
        if x<7:
            label.append(line.split('|')[0])
            label.append(line.split('|')[2])
            label.append(line.split('|')[3])
            label.append(line.split('|')[17])

    f.close()


with open('test.txt','w') as f:
    n = 0
    for i in label:
        if n%4 ==0:
            f.write('\r\n')
            f.write(i+'|')
        else:
            f.write(i+'|')
        n=n+1


with open('全部维度.txt','r') as f:
    lines = f.readlines()
    label = []
    n =0
    for line in lines:
        if n == 0 or n%2==0:
            label.append(line.split('|')[2])
        n=n+1



    f.close()
with open('test.txt','w') as f:
    n = 0
    for i in label:
        f.write(i)
        f.write('\r\n')
用于提取数据的代码如下,哪里有问题: “”" 从文件中提取特定格式的数据 “”" try: # os.makedirs(os.path.dirname(output_file), exist_ok=True) with open(input_file, 'r') as fin, open(output_file, 'w', newline='') as fout: writer = csv.writer(fout) writer.writerow(headers) # 跳过前84行不需要的数据 for _ in range(84): next(fin) # 读取第85行获取数据总个数 line85 = next(fin).split() if len(line85) < 2: raise ValueError("第85行格式错误,缺少第二个数字") if int(line85[1]) != num_bins: print(f"文件中每个数据包含{line85[1]}个FFT结果,程序声明每个数据包含{num_bins}个结果") print(f"共包含 {num_samples} 条数据记录,每条数据包括{num_bins}个FFT结果") # 跳过第86行 next(fin) # 提取有效数据行 (87, 90, 93, ...) records_extracted = 0 current_line = 87 while current_line < 87 + 3 * num_samples: try: data_line = next(fin).strip() # 跳过空行 if not data_line: current_line += 1 continue # 分割数据字段(假设原始数据是空格分隔) data_fields = data_line.split() data_fields.append(data_mode) # 写入CSV行 writer.writerow(data_fields) records_extracted += 1 # 跳过两行不需要的数据 for _ in range(2): next(fin) current_line += 3 print(f"成功提取 {records_extracted} 条数据记录") if records_extracted != num_samples: print(f"警告:提取记录数({records_extracted})与总数({num_samples})不一致") except FileNotFoundError: print(f"错误:文件 {input_file} 不存在") except Exception as e: print(f"处理过程中出错: {str(e)}")
最新发布
09-26
以下是我的代码,有问题吗? """ 从文件中提取特定格式的数据 """ try: os.makedirs(os.path.dirname(output_file), exist_ok=True) with open(input_file, 'r') as fin, open(output_file, 'w', newline='') as fout: writer = csv.writer(fout) writer.writerow(headers) # 跳过前84行不需要的数据 for _ in range(84): next(fin) # 读取第85行获取数据总个数 line85 = next(fin).split() if len(line85) < 2: raise ValueError("第85行格式错误,缺少第二个数字") total_count = int(line85[1]) print(f"文件包含 {total_count} 条数据记录") # 跳过第86行 next(fin) # 提取有效数据行 (87, 90, 93, ...) records_extracted = 0 current_line = 87 while current_line < 87 + 3 * total_count: try: data_line = next(fin).strip() # 跳过空行 if not data_line: current_line += 1 continue # 分割数据字段(假设原始数据是空格分隔) data_fields = data_line.split() data_fields.append(label) # 写入CSV行 writer.writerow(data_fields) records_extracted += 1 # 跳过两行不需要的数据 for _ in range(2): next(fin) current_line += 3 except StopIteration: print(f"警告:文件在行 {current_line} 提前结束") break print(f"成功提取 {records_extracted} 条数据记录") if records_extracted != total_count: print(f"警告:提取记录数({records_extracted})与第85行声明的总数({total_count})不一致") except FileNotFoundError: print(f"错误:文件 {input_file} 不存在") except Exception as e: print(f"处理过程中出错: {str(e)}")
09-19
import os # 定义数据集根目录 data_dir = "./datasets/nyuv2" # 定义各子目录路径 rgb_dir = os.path.join(data_dir, "rgb") depth_dir = os.path.join(data_dir, "depth") label_dir = os.path.join(data_dir, "labels") # 获取所有RGB文件名(带后缀) rgb_files = sorted([f for f in os.listdir(rgb_dir) if f.endswith(".png")]) # 提取RGB文件名中的唯一标识符(例如:image_0001_color.png -> 0001) def extract_id(rgb_filename): # 假设文件名格式为:prefix_id_suffix.png(例如:image_0001_color.png) parts = os.path.splitext(rgb_filename)[0].split("_") # 分割得到 ["image", "0001", "color"] return parts[1] # 提取中间的数字ID部分 # 构建文件名映射关系 file_pairs = [] for rgb_file in rgb_files: # 提取标识符(例如:0001) file_id = extract_id(rgb_file) # 构建预期的depthlabel文件名(根据实际命名规则调整) expected_depth_file = f"image_{file_id}_depth.png" # 假设depth文件格式 expected_label_file = f"image_{file_id}_label.png" # 假设label文件格式 # 检查文件是否存在 depth_path = os.path.join(depth_dir, expected_depth_file) label_path = os.path.join(label_dir, expected_label_file) if os.path.exists(depth_path) and os.path.exists(label_path): file_pairs.append((rgb_file, expected_depth_file, expected_label_file)) else: print(f"⚠️ 跳过 {rgb_file}: 未找到对应的depth/label文件") # 划分测试集(取后半部分) split_idx = len(file_pairs) // 2 test_pairs = file_pairs[split_idx:] # 生成test.txt(每行包含三个模态的路径) test_txt_path = os.path.join(data_dir, "test.txt") with open(test_txt_path, "w") as f: for rgb_file, depth_file, label_file in test_pairs: # 生成相对路径 rgb_rel = os.path.join("rgb", rgb_file) depth_rel = os.path.join("depth", depth_file) label_rel = os.path.join("labels", label_file) f.write(f"{rgb_rel}\n{depth_rel}\n{label_rel}\n") print(f"✅ 已生成测试集文件列表: {test_txt_path}") print(f"有效样本数: {len(test_pairs)} (原始文件数: {len(rgb_files)})") 这段代码由什么问题,为什么无法访问
03-21
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值