Python如何从文本末尾反向匹配首个停用词并截取对应内容
优化方案
高可读性高性能版本
先将停用词转集合提升匹配效率,直接倒序遍历分词列表索引,找到匹配项后直接切片拼接即可:
list_stop_words = ['for', 'the', 'with'] mystring = 'this is the car for the girl with the long nice red hair' stop_word_set = set(list_stop_words) words = mystring.split() for idx in range(len(words)-1, -1, -1): if words[idx] in stop_word_set: result = ' '.join(words[idx:]) break print(result) # 输出:the long nice red hair
这个方案避免了多次反转列表的开销,停用词查询效率从O(n)提升到O(1),逻辑清晰易维护。
一行实现版本
如果追求单行代码写法,可以用生成器表达式配合next()直接获取目标索引:
result = ' '.join(mystring.split()[(lambda sw, s: len(s) - 1 - next(i for i, w in enumerate(reversed(s)) if w in sw))(set(list_stop_words), mystring.split()):])
运行后得到的结果和预期完全一致。
内容的提问来源于stack exchange,提问作者JFerro
相关产品推荐
相关产品推荐

