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

如何用Python将特定格式数据转换为符合规则的目标列表?

Python实现输入数据到目标输出的转换方案

需求描述

将输入文本转换为指定格式,需遵循以下规则:

  • 匹配每个idx对应的所有行中的数值
  • 将size(十六进制字符串)转换为十进制后,若数值≥10,每10个数值后需添加1个额外空格(例如size为025即十进制25,需在第10、20个数值后各添加1次额外空格)

输入输出示例

输入(input.txt)

[00], idx=06, size=001
[06000] 00
[01], idx=07, size=001
[07000] 00
[02], idx=20, size=007
[20000] 00 00 00 00 40 00 00
[03], idx=33, size=002
[33000] 2b 03
[04], idx=45, size=015
[45000] ff 07 00 00 00 00 00 00 00 00 
[4500a] 00 00 00 00 00 00 00 00 00 00
[45014] 00 00 00 00 00

目标输出(output.txt)

[index]06 00
[index]07 00
[index]20 00 00 00 00 40 00 00
[index]33 2b 03
[index]45 ff 07 00 00 00 00 00 00 00  00 00 00 00 00

现有代码

import sys,os,re

def get_index(f):
    for line in f.readlines():
        if "idx" in line:
            yield line[10:12]

def main():
    with open("input.txt", "r") as f:
        with open("output.txt", "w") as oup:
            for line in get_index(f):
                oup.write('[index]' + line + '\n')

if __name__ == '__main__':
    main()         

完整解决方案

实现思路

  1. 按块解析输入文件:每个idx条目由一行带idx的定义行,以及后续若干行对应地址的数值行组成
  2. 用正则表达式提取idx、size(并转换为十进制),以及数值行中的所有数值
  3. 收集该idx对应的所有数值后,按规则在每10个数值后插入额外空格
  4. 拼接成目标格式的行,写入输出文件

完整代码

import re

def process_input(input_path, output_path):
    # 读取所有非空行
    with open(input_path, 'r') as f:
        lines = [line.strip() for line in f if line.strip()]
    
    output_lines = []
    line_idx = 0
    total_lines = len(lines)
    
    while line_idx < total_lines:
        # 处理当前idx定义行
        current_line = lines[line_idx]
        # 提取idx和十六进制size
        idx_match = re.search(r'idx=([0-9a-fA-F]{2})', current_line)
        size_match = re.search(r'size=([0-9a-fA-F]{3})', current_line)
        
        if not idx_match or not size_match:
            line_idx += 1
            continue
        
        target_idx = idx_match.group(1)
        size_hex = size_match.group(1)
        total_values = int(size_hex, 16)  # 转十进制总数值数
        
        line_idx += 1
        collected_values = []
        
        # 收集当前idx对应的所有数值行
        while line_idx < total_lines and 'idx' not in lines[line_idx]:
            # 提取该行的所有十六进制值,跳过第一个地址值
            hex_values = re.findall(r'[0-9a-fA-F]{2}', lines[line_idx])
            collected_values.extend(hex_values[1:])
            line_idx += 1
        
        # 按规则插入额外空格
        processed = []
        for val_pos, value in enumerate(collected_values[:total_values]):
            processed.append(value)
            # 每10个数值后添加额外空格,且不是最后一组
            if (val_pos + 1) % 10 == 0 and (val_pos + 1) < total_values:
                processed.append('')
        
        # 拼接成目标行并加入结果
        output_line = f'[index]{target_idx} {" ".join(processed)}'
        output_lines.append(output_line)
    
    # 写入输出文件
    with open(output_path, 'w') as oup:
        oup.write('\n'.join(output_lines))

if __name__ == '__main__':
    process_input('input.txt', 'output.txt')

代码说明

  • 正则提取:避免硬编码字符串索引,提升代码鲁棒性
  • 块处理:确保每个idx对应的所有数值行都被正确收集
  • 空格插入逻辑:通过在每10个数值后添加空字符串,join时会自动生成两个空格(符合示例中的格式要求)
  • 截断处理:只取前total_values个数值,避免多余数值干扰

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 07:55:20