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

如何统计用户输入中高频禁用词并输出指定格式的Top5结果

解决方案

你只需要修改生成top5的map逻辑,把原来仅提取单词的逻辑改成拼接单词与出现次数的格式即可。

修改后的核心代码

将原来的:

let top5 = sortedMatches.slice(0, 5).map(m => m[0]);

替换为:

let top5 = sortedMatches.slice(0, 5).map(m => `${m[0]} - ${m[1]}`);

完整修改后代码

let words = textWords.split(' ');
console.log('words', words)
let badWords = listOfBadWords.join('|');
let regex = new RegExp(badWords, 'gi');

let matches = words.reduce((acc, word) => {
  if (word.match(regex)) {
    let match = word.toLowerCase();
    acc[match] = (acc[match] || 0) + 1;
  }
  return acc;
}, {});

let sortedMatches = Object.entries(matches).sort((a, b) => b[1] - a[1]);
// 拼接成要求的"单词 - 次数"格式
let top5 = sortedMatches.slice(0, 5).map(m => `${m[0]} - ${m[1]}`);

console.log(top5); // 输出示例: ["badword1 - 5", "badword2 - 3", "badword3 - 2", ...]

修改后,top5数组中的每个元素都会以"单词 - 出现次数"的格式呈现,直接打印或使用该数组即可得到目标输出。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 04:15:42