编写一个函数查找一篇英文文章中出现频率最高的单词(由26个英文字母大小写构成),输出该单词及出现次数,不区分大小写,主要是正则和哈希表的运用
// 这种方法应该是查找出现频率最高的字母
function searchWord1(article){
if(!article)return;
// 参数处理,清除除了单词间空格外的文本中的所有空格,并转换所有字母为小写
article = article.trim().toLowerCase();
// 按照正则做单词的全局匹配 输出文章中的所有单词得到一个都是单词字符的数组
let wordList = article.match(/[a-z]+/g);
// 存储搜索过的单词
let visited = [];
// 单词的出现次数
let maxNum = 0;
// 出现频率最高的那个单词
let maxWord = '';
// 把数组还原成字符串形式
article = "" + wordList.join(" ")+"";
wordList.forEach((item)=>{
if(visited.indexOf(item) === -1){
visited.push(item);
// 新建正则对象
let word = new RegExp(""+item+"","g");
let num = article.match(word).length;
if(num>maxNum){
maxNum = num;
maxWord = item;
}
}
})
return maxWord + " " + maxNum;
}
// 另一种做法
function searchWord(article) {
if (!article) return;
// 基本处理
article = article.trim().toLowerCase();
// 正则切分成数组便于循环
let wordList = article.match(/[a-z]+/g);
console.log(wordList);
let maxWord = '';
let maxNum = 1;
let visited = {};
// 把文章切分成一个个字母空格的形式
// article = ""+wordList.join(" ")+"";
for (let i = 0; i < wordList.length; i++) {
if (visited[wordList[i]]) {
visited[wordList[i]]++;
if (visited[wordList[i]] > maxNum) {
maxNum = visited[wordList[i]];
maxWord = wordList[i];
}
} else {
visited[wordList[i]]=1;
}
}
return maxNum + " " + maxWord
}
console.log(searchWord('Each human being is born as something new, something that never existed before. Each is born with the capacity to win at life. Each person has a unique way of seeing, hearing, touching, tasting and thinking. Each has his or her own unique potentials---capabilities and limitations. Each can be a significant, thinking, aware, and creative being---a productive person, a winner.'))
版权声明:本文为m0_51123132原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。