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

在JavaScript中查找特定单词之后的所有后续单词

提取特定单词后的紧邻单词

需求说明

给定文本,提取所有出现在目标单词(如示例中的to)之后的第一个单词,最终返回包含这些单词的数组。以示例文本为例:

I want to deliver goods from Indonesia to India

提取to后的单词,结果应为['deliver', 'India']。

实现方案(Python)

直接通过字符串分割与遍历即可实现:

# 示例文本
text = "I want to deliver goods from Indonesia to India"
# 目标单词
target = "to"

# 将文本分割为单词列表
word_list = text.split()
result = []

# 遍历每个单词的索引
for idx in range(len(word_list)):
    # 检查当前单词是否为目标词,且下一个位置存在单词
    if word_list[idx] == target and idx + 1 < len(word_list):
        result.append(word_list[idx + 1])

print(result)  # 输出: ['deliver', 'India']

关键逻辑说明

  • 使用split()将文本按空格分割为单词数组,默认处理空格分隔的英文文本。
  • 遍历数组时,通过索引判断当前单词是否为目标词,同时确保不会越界(即目标词不在文本最后一位)。
  • 每找到一个目标词,就将其下一个单词加入结果数组。

扩展处理

如果需要处理带标点的文本(如"I want to deliver, goods from Indonesia to India."),可以先去除标点再分割:

import string

text = "I want to deliver, goods from Indonesia to India."
target = "to"

# 移除标点符号
clean_text = text.translate(str.maketrans('', '', string.punctuation))
word_list = clean_text.split()
result = []

for idx in range(len(word_list)):
    if word_list[idx] == target and idx + 1 < len(word_list):
        result.append(word_list[idx + 1])

print(result)  # 输出: ['deliver', 'India']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 12:35:17