在 JavaScript 中查找文本字符串中出现次数最多的三个单词
问题
我们需要编写一个接受英文字母字符串的JavaScript函数。我们的函数应该返回字符串中出现的前三个最频繁的单词。
示例
以下是代码-
const str = 'Python was developed by Guido van Rossum in the late eighties and early nineties at the National Research Institute for Mathematics and Computer Science in the Netherlands. Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68, SmallTalk, and Unix shell and other scripting languages. Python is copyrighted. Python source code is now available under the GNU General Public License (GPL)';
const findTopThree = (str = '') => {
str = str
.replace(/[^\w\s]|_/g, "")
.replace(/\s+/g, " ")
.toLowerCase();
const arr = str.split(' ');
const map = {};
arr.forEach(word => {
map[word] = (map[word] || 0) + 1;
});
const res = Array.from(Object.keys(map), key => [key, map[key]]);
res.sort((a, b) => b[1] - a[1]);
return [res[0][0], res[1][0], res[2][0]];
};
console.log(findTopThree(str));输出结果以下是控制台输出-
["python","the","and"]
热门推荐
10 年底拜年祝福语大全简短
11 宝宝祝福语诗意简短 古文
12 祝女儿出嫁简短祝福语
13 服装超市开业祝福语简短
14 下雪路滑祝福语简短
15 简短搞笑的虎年祝福语
16 高考毕业祝福语简短励志
17 梳子结婚蛋糕祝福语简短
18 虎年女孩出生祝福语简短