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

如何查找字符串中指定数组内单词相邻出现的连续片段

问题说明

需求为给定存储语句的目标字符串、由指定单词构成的匹配数组,找出字符串中所有连续相邻出现2个及以上数组内单词的文本片段。
原有手动枚举单词组合的实现最多支持3个单词的连续匹配,随着连续匹配长度上升,枚举的组合规模会指数级膨胀,需要通用、高效的实现方案。
示例参数与预期结果:

  • 待匹配单词数组:['cat','dog','and','the']
  • 待检索字符串:There is a dog and cat over there. The cat likes the dog.
  • 预期返回结果:['dog and cat','the dog','the cat']
实现方案

不需要枚举任何单词组合,采用单次线性扫描的思路即可实现,时间复杂度为O(n),无论连续匹配的单词长度是多少,性能都不会出现明显下降,完全规避组合爆炸问题:

  1. 先将待匹配的单词统一转为小写后存入哈希集合,实现单个单词是否命中的O(1)时间查询
  2. 对目标字符串做分词,提取出所有独立单词,匹配过程默认大小写不敏感(可根据需求调整为严格大小写匹配)
  3. 遍历分词结果,维护一个临时列表存储当前连续命中的单词:
    • 若当前单词在匹配集合中,直接加入临时列表
    • 若当前单词不在匹配集合中,先检查临时列表长度:如果长度≥2,就将列表内单词拼接为片段存入结果,之后清空临时列表
    • 整个分词列表遍历完成后,需要额外检查一次临时列表,避免字符串末尾的连续命中片段被遗漏
可直接运行的参考代码(Python)
import re

def find_consecutive_matches(target_words: list[str], text: str) -> list[str]:
    # 构建匹配词集合,统一转小写实现大小写不敏感匹配
    target_set = {word.lower() for word in target_words}
    # 提取文本中所有英文单词
    words = re.findall(r'[a-zA-Z]+', text)
    result = []
    current_streak = []
    
    for word in words:
        if word.lower() in target_set:
            current_streak.append(word)
        else:
            if len(current_streak) >= 2:
                # 拼接时统一转小写,和示例输出保持一致
                result.append(' '.join(w.lower() for w in current_streak))
            current_streak = []
    # 处理文本末尾残留的连续匹配段
    if len(current_streak) >= 2:
        result.append(' '.join(w.lower() for w in current_streak))
    return result

# 示例测试
if __name__ == "__main__":
    target_word_list = ['cat','dog','and','the']
    test_content = "There is a dog and cat over there. The cat likes the dog."
    print(find_consecutive_matches(target_word_list, test_content))
    # 输出结果:['dog and cat', 'the cat', 'the dog']

适配说明:如果需要严格区分大小写,删除代码中所有.lower()相关逻辑即可;如果是中文等其他语言场景,只需要把英文分词逻辑替换为对应语言的分词工具,后续的连续匹配逻辑完全通用,不需要修改。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 18:24:35