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

如何在Python中用正则清理信用卡交易CSV的交易名称?

信用卡交易名称清理方案:正则表达式 vs 其他方法

我正在清理美国运通信用卡账单的交易CSV数据,交易名称格式如下:
AplPay SUBWAY SCOTTSDALE AZ
POPEYES 8703 0000 TEMPE AZ
SALAD AND GO #1138 0PHOENIX AZ
所有交易名称末尾都带有数量不定的空格+2位州缩写(比如AZ),这些空格是用来对齐州缩写的。想请教:用正则表达式移除这部分内容是否合适?有没有更优的方案?

目前我用Python构建交易列表的代码如下:

AmextransList = []
fileName = 'amexActivityJune.csv'
cnt = 0
with open(fileName, newline='') as csvfile:
  spamreader = csv.reader(csvfile, delimiter=',')
  for row in spamreader:
    if cnt != 0:
      AmextransList.append(transaction(row[1], row[0], row[2]))
    cnt += 1

我的transaction类里定义了cleanTransaction方法,希望在这里完成交易名称的清理,当前类代码:

class transaction:
  name = ""
  date = ""
  amount = ""
  def __init__(self, n, d, a):
    self.name = n
    self.date = d
    self.amount = a
  def printTransaction(self):
    print("Name: ", self.name, " Amount: ", self.amount, " Date: ", self.date)

  def cleanTransaction(self): # 这里需要帮助
    # 移除末尾的____AZ部分
    # 其他工作就不麻烦StackOverflow了:)

方案分析

1. 正则表达式:合适且高效

正则表达式完全适配这个场景——你要匹配的是字符串末尾的任意数量空格+2位大写州缩写,规则明确无歧义。

可以使用这个正则模式:\s+[A-Z]{2}$,各部分含义:

  • \s+:匹配1个及以上的空格(覆盖所有对齐用的空格数量)
  • [A-Z]{2}:精准匹配2位大写字母的美国州缩写
  • $:锚定字符串末尾,确保只处理结尾的目标内容

在cleanTransaction中的实现:

import re

def cleanTransaction(self):
    # 移除末尾的空格+州缩写
    self.name = re.sub(r'\s+[A-Z]{2}$', '', self.name)
    # 可选:去除名称首尾可能残留的多余空格
    self.name = self.name.strip()

2. 非正则替代方案:字符串反向遍历

如果不想依赖正则模块,也可以通过字符串反向查找实现:

def cleanTransaction(self):
    # 从字符串末尾往前找第一个非空格字符的位置
    end_idx = len(self.name) - 1
    while end_idx >= 0 and self.name[end_idx].isspace():
        end_idx -= 1
    
    # 检查该位置之后是否是2位大写州缩写
    if end_idx + 2 <= len(self.name) - 1 and self.name[end_idx+1:].isupper() and len(self.name[end_idx+1:]) == 2:
        self.name = self.name[:end_idx+1].rstrip()
    else:
        # 没有匹配到目标内容时,仅去除首尾空格
        self.name = self.name.strip()

方案对比

  • 正则表达式:代码简洁、可读性强(只要理解基础正则规则),处理速度足够快,是这类规则明确的文本处理场景的最优选择。
  • 非正则方案:无需引入re模块,适合对正则不熟悉的开发者,但代码相对繁琐,需要手动处理边界情况(比如名称末尾本身有大写字母但并非州缩写的场景)。

完整修改后的transaction类示例

import re

class transaction:
    def __init__(self, n, d, a):
        self.name = n
        self.date = d
        self.amount = a

    def printTransaction(self):
        print(f"Name: {self.name} Amount: {self.amount} Date: {self.date}")

    def cleanTransaction(self):
        # 使用正则移除末尾的空格+州缩写
        self.name = re.sub(r'\s+[A-Z]{2}$', '', self.name)
        # 去除首尾多余空格
        self.name = self.name.strip()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 08:57:14