Node.js如何按句号(.)和问号(?)拆分句子并统计各句单词数
Node.js 句子拆分与单词统计功能实现
功能需求
Node.js开发场景下需实现如下功能:按句号(.)和问号(?)拆分目标句子,同时统计每个拆分后句子的单词数量。
参考示例
输入句子:"i am a boy. who are you?"
预期拆分结果共3句:
- i am a boy
- who are you
- ''
对应单词统计结果:第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
相关产品推荐
相关产品推荐

