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

Python如何提取字符串特定片段并导出为指定格式的CSV文件?

Python处理固定宽度字符串生成CSV的更优方案

你遇到的是固定宽度字段结构化字符串的解析场景,硬编码索引切片的核心问题是可维护性差,一旦字段宽度、顺序调整就要修改大量切片代码,更优的方案是把字段规则抽成独立配置,用通用逻辑完成解析,灵活度和可维护性会高很多。


实现思路

  • 把所有字段的宽度、转换规则、输出格式整理成配置列表,和业务逻辑解耦
  • 遍历配置自动按宽度截取子串,统一做格式转换
  • 直接用csv模块写入结果

代码实现

import csv

# 字段配置:(字段宽度, 转换函数, 输出格式化模板)
# 后续调整字段规则只需修改该配置,不需要改动解析逻辑
FIELD_CONFIG = [
    (1, lambda x: int(x.strip()), "{}"),  # 目标第一个字段1
    (1, lambda x: int(x.strip()), "{}"),  # 目标第二个字段1
    (11, lambda x: float(x.strip()), "{:.5f}"),  # 1663.315780 -> 1663.31578
    (11, lambda x: float(x.strip()), "{:.3e}"),  # 6.045E-26 -> 6.045e-26
    (8, lambda x: float(x.strip()), "{:.4f}"),  # 6.292E-01 -> 0.6292
    (6, lambda x: float(x.strip()), "{:.4f}"),  # .06980 -> 0.0698
    (4, lambda x: float(x.strip()), "{:.3f}"),  # .304 -> 0.304
    (9, lambda x: float(x.strip()), "{:.4f}"),  # 2724.04150 -> 2724.0415
    (3, lambda x: float(x.strip()), "{:.2f}"),  # .64 -> 0.64
    (8, lambda x: float(x.strip()), "{:.5f}"),  # -.009550 -> -0.00955
    # 如需保留后续字段,直接在配置列表追加对应规则即可
]

def parse_fixed_width_line(s: str, config: list) -> list:
    res = []
    current_pos = 0
    for width, converter, formatter in config:
        # 按宽度截取子串
        substring = s[current_pos:current_pos+width].strip()
        current_pos += width
        # 执行转换+格式化,自动把科学计数法的E转成小写e
        converted_val = converter(substring)
        res.append(formatter.format(converted_val).lower())
    return res

# 测试用原始字符串
raw_str = " 11 1663.315780 6.045E-26 6.292E-01.06980.304 2724.04150.64-.009550          1 0 0          0 1 0  8  0  8        7  5  3      355243301884671724    17.0   15.0"
output_path = "output.csv"

with open(output_path, "w", newline="", encoding="utf-8") as f:
    writer = csv.writer(f)
    parsed_row = parse_fixed_width_line(raw_str, FIELD_CONFIG)
    writer.writerow(parsed_row)

方案优势

  • 灵活性高:字段宽度、转换规则、输出格式调整时,仅需要修改FIELD_CONFIG配置即可,不需要修改解析逻辑
  • 可复用性强:parse_fixed_width_line是通用函数,所有固定宽度字符串解析场景都可以直接使用
  • 可读性好:所有字段规则集中在配置里,后续维护不用对着硬编码的索引一个个数位置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 18:54:01