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

Python如何提取特殊字符∑分割后的第n位或最后一段数据

Python提取每行最后一个「∑」后内容的实现方案

代码实现

补全你提供的mapper函数

def mapper(_, line):
    # 过滤空行
    if not line.strip():
        return
    words = line.split('∑')
    # 取拆分列表最后一个元素,去除首尾空白/换行符
    return words[-1].strip()

完整文件处理代码(可直接得到预期输出)

output_list = []
# 替换为你的实际文件路径
file_path = "data.txt"

with open(file_path, "r", encoding="utf-8") as f:
    # 跳过表头行,无需跳过可删除此行
    next(f)
    for line in f:
        line = line.strip()
        if not line:
            continue
        last_content = line.split("∑")[-1]
        output_list.append(last_content)

print(output_list)

运行结果

对应你提供的示例文本,运行后输出为:

['4.0.3 and up', '4.0.3 and up']

逻辑说明

  • 调用split('∑')会将整行内容按分隔符拆分为列表,负索引[-1]可直接取到列表的最后一个元素,也就是最后一个「∑」后的内容
  • 增加空行判断、strip()处理是为了过滤无效行、去除行尾的换行符和多余空白,避免结果出现冗余字符
  • 如果某行不存在「∑」字符,split返回的列表仅有一个元素,[-1]会返回整行内容,符合需求逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 17:15:11