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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 16:06:07