如何按指定字符分割字符串并提取最后分组的目标部分
按元音分割单词并处理最后分组的实现方案
给定数据
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': ''}
代码说明
- 分割单词:用
vowel_split_re匹配任意元音作为分隔符,把单词拆成多段后直接取最后一段 - 清理开头元音:用
strip_start_vowels_re匹配最后一段开头的连续元音,用空字符串替换掉这些元音,得到最终结果
内容的提问来源于stack exchange,提问作者shantanuo
相关产品推荐
相关产品推荐

