Python如何用指定列表对应值替换字符串末尾匹配前缀的单词
实现方案
问题点修正
你原有代码的两处逻辑偏差:
split(' ', 1)[-1]是按首个空格拆分字符串拿后半段,无法正确提取最后一个单词,需用rsplit(' ', 1)从右往左拆分1次,拆分结果的第二个元素就是最后一个单词- 不需要调用
replace方法,直接拼接前缀内容和匹配到的前缀即可,避免误替换字符串其他位置的相同内容
完整可运行代码
my_list = ['en','di','fi','ope'] test_strings = ['you cannot enter', 'the wound is open', 'the house is clean'] output = [] for entry in test_strings: # 拆分出前面的内容和最后一个单词 parts = entry.rsplit(' ', maxsplit=1) if len(parts) == 1: # 处理字符串只有一个单词的边界场景 front_content = '' last_word = parts[0] else: front_content, last_word = parts matched_prefix = None # 遍历匹配前缀 for prefix in my_list: if last_word.startswith(prefix): matched_prefix = prefix break if matched_prefix: output.append(f"{front_content} {matched_prefix}" if front_content else matched_prefix) else: output.append(entry) print(output) # 输出结果:['you cannot en', 'the wound is ope', 'the house is clean']
扩展说明
如果需要优先匹配更长的前缀(比如同时存在o和ope两个前缀时,优先用更长的ope),只需在遍历前将前缀列表按长度倒序排序即可:
# 按前缀长度倒序排列,优先匹配更长的前缀 sorted_prefixes = sorted(my_list, key=lambda x: len(x), reverse=True) # 后续遍历sorted_prefixes做匹配即可
内容的提问来源于stack exchange,提问作者zara kolagar
相关产品推荐
相关产品推荐

