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

Python新手求助:按百分比拆分账单金额并生成独立行

账单金额百分比拆分问题解决

需求

  • 读取TXT文件中的账单数据,每行包含Date, Period, NumberBill, Amount, KEY, WHAT字段
  • KEY为TEAM的账单,将Amount按30%、20%、50%比例拆分,每个拆分结果生成独立新行,替换对应Amount值
  • KEY为PERSON的账单,保持原行不变

原始数据

['Date', 'Period', 'NumberBill', 'Amount', 'KEY', 'WHAT\n']
['31.01.2022', '2', 'BILL3', '-1800.00', 'TEAM', 'BILL\n']
['03.02.2022', '2', 'BILL2', '644.00', 'PERSON','BILL\n']
['03.02.2022', '2', 'BILL1', '150.00', 'TEAM', 'BILL']

当前问题

现有代码会将拆分结果追加到原行末尾,不符合要求:

现有代码

filepath = "test.txt"
file = open(filepath, "r")
for i in file:
 iSplit = i.split(";")

 percentage1 = 0.30
 percentage2 = 0.20
 percentage3 = 0.50
 result1 = 0
 result2 = 0
 result3 = 0

 if iSplit[4] == 'TEAM':
     result1 = float(iSplit[3]) * percentage1
     result2 = float(iSplit[3]) * percentage2
     result3 = float(iSplit[3]) * percentage3
     iSplit.append(round(result1, 2))
     iSplit.append(round(result2, 2))
     iSplit.append(round(result3, 2))
     print(iSplit)

当前错误输出

['31.01.2022', '2', 'BILL3', '-1800.00', 'TEAM', 'BILL\n', -540.0, -360.0, -900.0]
['03.02.2022', '2', 'BILL1', '150.00','TEAM', 'BILL', 45.0, 30.0, 75.0]

修正后的代码

filepath = "test.txt"
# 定义拆分比例
split_ratios = [0.3, 0.2, 0.5]

with open(filepath, "r") as file:
    for line in file:
        # 去除首尾空白与列表格式标记,提取字段
        cleaned_line = line.strip().strip('[]')
        fields = [field.strip("'\n") for field in cleaned_line.split(', ')]
        
        # 跳过表头行
        if fields[0] == 'Date':
            continue
        
        date, period, bill_num, amount_str, key, what = fields
        
        if key == 'PERSON':
            # 直接输出原行
            print(f"['{date}', '{period}', '{bill_num}', '{amount_str}', '{key}','{what}']")
        elif key == 'TEAM':
            amount = float(amount_str)
            for ratio in split_ratios:
                split_amount = round(amount * ratio, 2)
                # 格式化金额为两位小数的字符串
                split_amount_str = f"{split_amount:.2f}"
                # 生成并输出拆分后的新行
                print(f"['{date}', '{period}', '{bill_num}', '{split_amount_str}', '{key}', '{what}']")

期望输出

['03.02.2022', '2', 'BILL2', '644.00', 'PERSON','BILL']
['31.01.2022', '2', 'BILL3', '-540.00', 'TEAM', 'BILL']
['31.01.2022', '2', 'BILL3', '-360.00', 'TEAM', 'BILL']
['31.01.2022', '2', 'BILL3', '-900.00', 'TEAM', 'BILL']
['03.02.2022', '2', 'BILL1', '45.00', 'TEAM', 'BILL']
['03.02.2022', '2', 'BILL1', '30.00', 'TEAM', 'BILL']
['03.02.2022', '2', 'BILL1', '75.00', 'TEAM', 'BILL']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 06:30:39