写一个方法找出一段话里面出现频率最多的词

在前端开发中,我们可以使用JavaScript来编写一个方法,该方法能够找出一段话中出现频率最多的词。以下是一个简单的示例:

function findMostFrequentWord(text) {
  // 将文本转换为小写,以便不区分大小写
  const lowercasedText = text.toLowerCase();
  
  // 使用正则表达式将文本拆分为单词数组
  // 这个正则表达式会匹配字母数字字符,并且会用空格替换非字母数字字符
  const words = lowercasedText.replace(/[^\w\s]|_/g, "").replace(/\s+/g, " ").split(/\s+/);
  
  // 创建一个对象来存储每个单词的频率
  const wordFrequency = {};
  
  // 遍历单词数组,并更新每个单词的频率
  for (let word of words) {
    if (wordFrequency[word]) {
      wordFrequency[word]++;
    } else {
      wordFrequency[word] = 1;
    }
  }
  
  // 找出出现频率最高的单词
  let mostFrequentWord = '';
  let highestFrequency = 0;
  
  for (let word in wordFrequency) {
    if (wordFrequency[word] > highestFrequency) {
      mostFrequentWord = word;
      highestFrequency = wordFrequency[word];
    }
  }
  
  // 返回出现频率最高的单词及其频率
  return { word: mostFrequentWord, frequency: highestFrequency };
}

// 示例用法
const text = "This is a test. This test is fun! Fun is good.";
const result = findMostFrequentWord(text);
console.log(result); // 输出:{ word: 'is', frequency: 3 }

这个方法首先将输入的文本转换为小写,并使用正则表达式将其拆分为单词数组。然后,它遍历这个数组,并使用一个对象来存储每个单词的出现频率。最后,它找出出现频率最高的单词,并返回一个包含该单词及其频率的对象。

来源链接:https://www.cnblogs.com/ai888/p/18681289

请登录后发表评论

    没有回复内容