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

Python不使用pandas如何将按~分隔的优惠码拆分为多条独立记录

代码修改实现方案
import csv
import json

with open('tran_test.csv') as file:
    dict_input = csv.reader(file, delimiter='|')
    next(dict_input, None)
    output = []
    for line in dict_input:
        promotion_code = line[0]
        promotion_name = line[1].strip()
        coupon_code = line[2]
        coupon_name = line[3]
        coupon = []
        
        # 按~拆分优惠活动编码和名称,去除前后空格过滤空项
        promo_codes = [code.strip() for code in promotion_code.split('~') if code.strip()]
        promo_names = [name.strip() for name in promotion_name.split('~') if name.strip()]
        
        # 遍历生成所有拆分后的优惠活动记录
        for code, name in zip(promo_codes, promo_names):
            pro_code = {
                'coupon_code': code,
                'type': 'promo_code',
                'description': name,
                'redeem': 'false'
            }
            coupon.append(pro_code)
        
        # 处理优惠券记录
        if coupon_code.strip():
            cou_code = {
                'coupon_code': coupon_code,
                'type': 'coupon_code',
                'description': coupon_name,
                'redeem': 'false'
            }
            coupon.append(cou_code)

        output_obj = {'coupons': coupon}
        output.append(output_obj)

print(json.dumps(output))

核心修改说明

  • 新增拆分逻辑:将读取到的优惠活动编码、优惠活动名称按~分割,同时去除每个拆分结果的前后空白字符,过滤无效空值
  • 重构原有多分支判断逻辑,先统一生成所有拆分后的优惠活动对象,再处理优惠券对象添加,代码更简洁易维护
  • 修复原代码中同时存在优惠活动和优惠券时,coupon变量被赋值为元组的问题,统一使用列表存储,符合JSON输出格式要求
  • 自动适配多组~分隔的优惠活动内容,无需额外修改逻辑即可支持更多活动拆分场景

用你提供的CSV样例数据运行以上代码,输出结果和你期望的结果完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 07:57:01