You need to enable JavaScript to run this app. 如何从Python列表中提取姓名并移除其余无关字符串
优惠活动
大模型
产品
解决方案
定价
更多

如何从Python列表中提取姓名并移除其余无关字符串

从给定列表提取对应姓名的实现方法

结合你提供的列表固定格式,可直接落地两种提取方案:

方案1:基于固定换行拆分(适配当前给定的列表结构)

从你执行print(my_list[0])的输出可以看到,每个列表元素都是被换行符分隔为固定三段:

  • 第一段:固定文本 view profile for
  • 第二段:目标姓名
  • 第三段:以 located at 开头的地址描述

直接通过列表推导式批量拆分即可,代码如下:

my_list = [
    'view profile for\nAli Safaei\nlocated at 1010-650 West Georgia St Vancouver',
    'view profile for\nBrian M. Baird\nlocated at 103-1185 West Georgia St Vancouver',
    'view profile for\nKarim A. Lalani\nlocated at 1308 Alberni St Vancouver',
    'view profile for\nNishant Goswami\nlocated at 201-1743 Robson St Vancouver',
    'view profile for\nEric P.J. Bussieres\nlocated at 201-1128 Hornby St Vancouver'
]

# 按换行拆分后取下标为1的元素,额外strip去除首尾多余空白
name_list = [item.split('\n')[1].strip() for item in my_list]
print(name_list)

运行代码后得到的提取结果为:

['Ali Safaei', 'Brian M. Baird', 'Karim A. Lalani', 'Nishant Goswami', 'Eric P.J. Bussieres']

方案2:正则匹配提取(适配后续格式变动场景)

如果后续列表的换行规则不固定(比如姓名前后有多余空格、换行数量不统一),可以通过匹配两个固定标识之间的内容完成提取,兼容格式小偏差,避免提取失败,代码如下:

import re

# 正则匹配"view profile for"和"located at"之间的文本,自动兼容换行、多余空格
name_list = [re.search(r'view profile for\s*(.*?)\s*located at', item).group(1) for item in my_list]

逻辑说明:正则中的\s会匹配所有空白字符(换行、空格、制表符),不管两个固定标识之间有多少个换行、首尾多少空格,都能精准提取到中间的姓名内容。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.04 13:06:04