You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何读取含多ID的结构化数据文件并生成独立CSV文件

文本数据转独立CSV文件解决方案

输入数据结构

FIXED=0
LINES=1
POINTS=5
390 397
390 396
389 395
389 394
388 393
IMAGE=Name1.jpg
ID=1 
FIXED=0
LINES=1
POINTS=4
255 503
256 502
256 501
256 500
IMAGE=Name2.jpg
ID=2 
FIXED=0
LINES=1
POINTS=6
262 431
262 430
262 429
262 428
262 427
262 426
IMAGE=Name3.jpg
ID=3 

需求说明

  • 每个条目(FIXED至ID之间的内容)生成独立CSV文件,文件名对应IMAGE=后的名称(例如Name1.csv)
  • CSV文件第一列为条目内数字行的第一列,第二列为数字行的第二列
  • 丢弃FIXED=0、LINES=1、POINTS=N、ID=N这类行
  • POINTS与IMAGE之间的数字行数不固定,需自适应处理

实现方案(Python脚本)

import os

def parse_and_convert(input_file):
    current_points = []
    current_image = None

    with open(input_file, 'r') as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            # 跳过不需要的配置行
            if line.startswith(('FIXED=', 'LINES=', 'ID=')):
                continue
            # 捕获图像文件名并触发CSV写入
            if line.startswith('IMAGE='):
                # 先处理上一个条目(如果存在)
                if current_image and current_points:
                    csv_filename = current_image.replace('.jpg', '.csv')
                    with open(csv_filename, 'w') as csv_f:
                        for point in current_points:
                            csv_f.write(f"{point[0]},{point[1]}\n")
                    print(f"生成文件: {csv_filename}")
                # 重置当前条目数据
                current_image = line.split('=')[1].strip()
                current_points = []
                continue
            # 收集坐标点数据
            coords = line.split()
            if len(coords) == 2:
                current_points.append(coords)
        # 处理最后一个条目
        if current_image and current_points:
            csv_filename = current_image.replace('.jpg', '.csv')
            with open(csv_filename, 'w') as csv_f:
                for point in current_points:
                    csv_f.write(f"{point[0]},{point[1]}\n")
            print(f"生成文件: {csv_filename}")

# 替换为你的输入文件路径
parse_and_convert('input_data.txt')

使用步骤

  1. 将上述代码保存为convert.py
  2. 把待处理的文本数据保存为input_data.txt(或修改脚本中input_file参数为你的文件路径)
  3. 运行脚本:python convert.py
  4. 脚本会在当前目录自动生成所有对应名称的CSV文件

内容的提问来源于stack exchange,提问作者Yugo Amaril

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 15:53:38