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

Python如何从给定字符串生成1、2、3词长度的连续子串组合

Python获取指定长度连续词串的最高效实现方案

需求说明

给定任意字符串,拆分出单词后提取所有1词、2词、3词长度的连续子串。

方案分析

你目前的实现逻辑正确,可读性强,中小文本场景下性能完全达标,时间复杂度为O(N)(N为拆分后的单词总数),已经是该需求下的最优时间复杂度。
如果追求更高性能,可以参考下面的优化方案:

方案1:列表推导式(高性能全量存储)

相比显式for循环+append的写法,列表推导式可以减少Python层面的循环开销,运行速度提升约20%~30%:

s = "This is the example string of which I want to generate subsequent combinations"
words = s.split()
ans = [
    " ".join(words[i:i+ln])
    for ln in [1,2,3]
    for i in range(len(words) - ln + 1)
]

方案2:生成器实现(超大文本场景省内存)

如果处理的文本量极大、不需要一次性持有所有结果,用生成器可以避免占用大量内存,适合迭代遍历场景:

def get_ngrams(s, n_list=[1,2,3]):
    words = s.split()
    for ln in n_list:
        for i in range(len(words) - ln + 1):
            yield " ".join(words[i:i+ln])

# 使用示例
s = "This is the example string of which I want to generate subsequent combinations"
ans = list(get_ngrams(s))

注意事项

  • 上述所有方案默认用空格拆分单词,如果你需要处理带标点的自然语言,可以替换s.split()为对应的分词逻辑
  • 如果需要扩展其他长度的n词串,只需要修改n_list的取值即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 07:09:01