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

Node.js如何按句号(.)和问号(?)拆分句子并统计各句单词数

Node.js 句子拆分与单词统计功能实现

功能需求

Node.js开发场景下需实现如下功能:按句号(.)和问号(?)拆分目标句子,同时统计每个拆分后句子的单词数量。

参考示例

输入句子:"i am a boy. who are you?"
预期拆分结果共3句:

  1. i am a boy
  2. who are you
  3. ''
    对应单词统计结果:第1句共4个单词,第2句共3个单词,第3句为空。

实现代码

function splitSentenceAndCountWords(input) {
  // 按.和?拆分输入字符串
  const sentenceList = input.split(/[.?]/);
  // 遍历统计每个句子的单词数
  const countResult = sentenceList.map(item => {
    // 按空格拆分单词,过滤空字符避免连续空格、首尾空格干扰
    const validWords = item.trim().split(/\s+/).filter(word => word);
    return {
      content: item,
      wordCount: validWords.length
    }
  });
  return {
    sentenceList,
    countResult
  }
}

// 测试用例
const testInput = "i am a boy. who are you?";
const { sentenceList, countResult } = splitSentenceAndCountWords(testInput);
console.log("拆分结果:", sentenceList);
countResult.forEach((res, idx) => {
  const tip = res.wordCount ? `第${idx+1}句共${res.wordCount}个单词` : `第${idx+1}句为空`;
  console.log(tip);
})

运行输出

拆分结果: [ 'i am a boy', ' who are you', '' ]
第1句共4个单词
第2句共3个单词
第3句为空

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 23:27:00