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

如何按指定规则为列表字符串中的姓名添加连字符?

解决方案:Python字符串处理实现需求

要实现这个按规则插入连字符的需求,我们可以用Python来处理,核心是先拆分字符串结构,再根据姓名部分的特征判断分割点,具体代码和解释如下:

original_list = [
    'Carter Copeland Melius Research LLC - Founding Partner, President and Research Analyst of Aerospace & Defense\n',
    'Gregory D. Smith The Boeing Company - CFO and Executive VP of Enterprise Operations, Finance & Strategy\n',
    'Maurita B. Sutedja The Boeing Company - VP of IR\n'
]

processed_list = []

for item in original_list:
    # 先去除末尾换行符,再分割成「姓名+公司」和「职位」两部分
    item_clean = item.rstrip('\n')
    name_company_part, position = item_clean.split(' - ', 1)
    
    # 把姓名+公司部分拆成单词列表
    words = name_company_part.split()
    
    # 判断第二个单词是否包含点号,确定姓名的长度
    if '.' in words[1]:
        # 第二个单词带点,姓名取前3个单词
        name = ' '.join(words[:3])
        company = ' '.join(words[3:])
    else:
        # 第二个单词不带点,姓名取前2个单词
        name = ' '.join(words[:2])
        company = ' '.join(words[2:])
    
    # 拼接成目标格式,再加上换行符
    processed_item = f"{name} - {company} - {position}\n"
    processed_list.append(processed_item)

# 输出结果
for line in processed_list:
    print(line, end='')

代码逻辑解释:

  1. 预处理字符串:先去掉每个字符串末尾的换行符,再用' - '分割成「姓名+公司」和「职位」两部分,避免职位部分的空格干扰姓名和公司的拆分。
  2. 拆分单词判断规则:把「姓名+公司」拆成单词列表后,检查第二个单词是否包含.:
    • 如果包含(比如Gregory D. Smith中的D.),说明姓名是前3个单词,剩下的是公司名;
    • 如果不包含(比如Carter Copeland),说明姓名是前2个单词,剩下的是公司名。
  3. 拼接目标格式:按照姓名 - 公司 - 职位的格式拼接字符串,最后加上换行符还原原格式。

运行这段代码后,就能得到你想要的转换结果啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 14:47:45