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

如何按指定字符分割字符串并提取最后分组的目标部分

按元音分割单词并处理最后分组的实现方案

给定数据

groups = ['a', 'e', 'i', 'o', 'u']
strings = ['testing', 'tested', 'fisherman', 'sandals', 'name']

需求

  • 按groups里的元音字符分割单词,例如"tested"会被分割成"t + est + ed"
  • 提取分割后的最后一个分组,再移除该分组开头所有属于groups的字符,比如"ed"处理后返回"d"

预期输出

expected={'testing':'ng', 'tested':'d', 'fisherman':'n', 'sandals':'ls', 'name':''}

解决方法

你已经知道单个字符分割可以用'tested'.split('e')[-1],但多元音的情况可以用正则表达式一次性搞定:

完整代码

import re

groups = ['a', 'e', 'i', 'o', 'u']
strings = ['testing', 'tested', 'fisherman', 'sandals', 'name']

# 生成匹配任意元音的正则表达式
vowel_split_re = re.compile(f'[{"".join(groups)}]')
# 生成匹配开头连续元音的正则表达式
strip_start_vowels_re = re.compile(f'^[{"".join(groups)}]+')

result_dict = {}
for word in strings:
    # 按元音分割单词,取最后一段
    last_segment = vowel_split_re.split(word)[-1]
    # 去掉这段开头的所有元音
    cleaned_segment = strip_start_vowels_re.sub('', last_segment)
    result_dict[word] = cleaned_segment

print(result_dict)
# 输出结果和预期一致:{'testing': 'ng', 'tested': 'd', 'fisherman': 'n', 'sandals': 'ls', 'name': ''}

代码说明

  1. 分割单词:用vowel_split_re匹配任意元音作为分隔符,把单词拆成多段后直接取最后一段
  2. 清理开头元音:用strip_start_vowels_re匹配最后一段开头的连续元音,用空字符串替换掉这些元音,得到最终结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 03:35:19