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

如何用output.py正确格式化读取trans.txt中的交易数据?

解决交易数据拆分问题

首先得指出你原来的output.py为啥不行:你用了line.split()按空格拆分,但trans.txt里的交易数据是完全连在一起的,没有任何空格分隔,这样执行的时候肯定会报错,因为split出来的内容根本没法分成价格、卡号、描述三个部分。

要搞定这个问题,我们得先分析现有trans.txt的结构:

  • 每个交易以7位数字开头(这是save_transactions里把价格乘100后用%07d格式化的结果)
  • 接下来是纯数字的信用卡号
  • 最后是描述(非数字开头的字符串)
  • 多个交易直接拼接在一起

基于这个结构,我们可以用正则表达式先拆分出每个交易块,再在每个块里拆分字段。修改后的output.py代码如下:

import re

# 读取整个交易文件的内容
with open("trans.txt", "r") as f:
    content = f.read().strip()

# 用正则匹配所有交易块:每个交易以7位数字开头,直到下一个7位数字出现前结束
transaction_blocks = re.findall(r'\d{7}(?:(?!\d{7}).)*', content)

for block in transaction_blocks:
    # 提取前7位作为价格
    price = block[:7]
    # 处理剩余部分,拆分信用卡号和描述
    remaining = block[7:]
    
    # 找到第一个非数字字符的位置,以此拆分卡号和描述
    split_pos = 0
    while split_pos < len(remaining) and remaining[split_pos].isdigit():
        split_pos += 1
    
    creditcard = remaining[:split_pos]
    description = remaining[split_pos:]
    
    # 格式化输出
    print(f"price : {price}")
    print(f"credit card : {creditcard}")
    print(f"description : {description}")
    print("---")  # 用分隔线区分不同交易,可选

运行这段代码后,就能得到你期望的输出:

price : 0000200
credit card : 3685754754275
description : LATTE
---
price : 0000126
credit card : 7862587458742584
description : MUFFIN
---
price : 0000323
credit card : 786478547854785
description : FILTER
---

额外建议:优化数据写入方式

其实这个问题根源在于transmod.py里的save_transactions没有给字段加分隔符,导致读取时很难拆分。如果可以修改写入逻辑,建议给每个字段加上分隔符(比如逗号),并且每个交易占一行,这样读取会简单很多:

修改后的transmod.py:

def save_transactions(price, credit_card, description):
    with open("trans.txt", "a+") as file:
        # 用逗号分隔字段,每个交易单独一行
        file.write(f"{price*100:07d},{credit_card},{description}\n")

对应的简化版output.py:

with open("trans.txt", "r") as f:
    for line in f:
        line = line.strip()
        if not line:
            continue
        price, creditcard, description = line.split(',')
        print(f"price : {price}")
        print(f"credit card : {creditcard}")
        print(f"description : {description}")
        print("---")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 21:27:28