简体   繁体   English

如何计算每个单词在字符串中出现的次数?

[英]How do I count the number of times each word appears in a string?

I'm learning JavaScript now and I'm working on a function that will count how many times words show up in a string, then spits out the answer as an object. 我现在正在学习JavaScript,并且正在开发一个函数,该函数将计算单词在字符串中出现的次数,然后将答案作为对象吐出来。 Per some suggestions on similar threads on this site, I've decided to use .split and a counter function to make a two-dimensional array, then populate an object with the results. 根据该站点上类似线程的一些建议,我决定使用.split和一个计数器函数来制作二维数组,然后使用结果填充对象。 I was running tests with sample texts, when I ran into some trouble with certain strings. 当我遇到某些字符串问题时,我正在用示例文本运行测试。 I can't figure out why some of the counters are showing up as undefined. 我不知道为什么某些计数器显示为未定义。

function countWords(str) {
  var answer = {};
  if (str === '') {
    return answer;
  }
  var strArray = [];
  strArray = str.split(' ');
  //strArray is an array that holds the words as separate strings
  console.log('strArray: ' + strArray);
  var resultWords = [];
  var resultCount = [];
  var counter = 0;

  // only if the word doesnt show up in resultWords, push it in, and increase the counter. if it has shown up, disregard
  for (var i = 0; i<strArray.length; i++) {
    counter = 0;
    if (resultWords.indexOf( strArray[i] ) === -1)  {
      resultWords.push(strArray[i]);
      counter += 1;
      // if the word shows up again, increase the counter
      for (var j = i + 1; j < strArray.length; j++) {
        if (resultWords[i] === strArray[j]) {
          counter += 1;
        }
        // push to resultCount the counter for each word
        resultCount[i] = counter;
      }
    }
    // create an object where the key is the word from resultWords and the value is the number from wordCount
    for (var k = 0; k < resultWords.length; k++) {
      answer[ resultWords[k] ] = resultCount[k];            
    }
  }
  console.log('resultWords: ' + resultWords);
  console.log('resultCount: ' + resultCount);
  return answer;
}

var sample = 'how now brown cow how now';
console.log(sample);
var output = countWords( sample ); 

I find that when I use the words "this" and "is" in my sample, I'm often returning "undefined" as the word count for those words. 我发现在示例中使用单词“ this”和“ is”时,我经常返回“ undefined”作为这些单词的单词计数。 For example, "to be or not to be" returns "undefined" for "that" and "is." 例如,“成为或不成为”将为“那个”和“是”返回“未定义”。 Can someone help elucidate what's going on here? 有人可以帮助阐明这里发生了什么吗? Thank you. 谢谢。

Your code is unreadable: 您的代码不可读:

  • too long blocks of code 太长的代码块
  • non-informative variable names (eg answer ) 非信息性的变量名(例如answer

Next, your algorithm is very slow: you can count words by parsing the whole array only once. 其次,您的算法非常慢:您可以通过仅解析整个数组一次来计数单词。

Last but not least, you should create the answer array outside the loop. 最后但并非最不重要的一点是,您应该在循环外部创建answer数组。

Here's a shorter implementation that use modern javascript features (for the sake of learning): 这是使用现代javascript功能的较短实现(出于学习目的):

function countWords(str) {
  const wordCounts = new Map()
  str.split(' ').forEach(word => {
    const currentWordCount = wordCounts.get(word) || 0
    wordCounts.set(word, currentWordCount+1)
  })

  /* Reproduce your output */
  const resultWords = [...wordCounts.keys()]
  const resultCount = [...wordCounts.values()]
  console.log('resultWords: ' + resultWords);
  console.log('resultCount: ' + resultCount);

  return wordCounts
}

On older js environment, you cannot use Map and arrow functions: 在较旧的js环境中,不能使用Map和arrow函数:

function countWords(str) {
  const wordCounts = {}
  str.split(' ').forEach(function(word) {
    const currentWordCount = wordCounts[word] || 0
    wordCounts[word] = currentWordCount+1
  })

  /* Reproduce your output */
  const resultWords = Object.keys(wordCounts)
  const resultCount = resultWords.map(function(word) { return wordCounts[word] })
  console.log('resultWords: ' + resultWords);
  console.log('resultCount: ' + resultCount);

  return wordCounts
}

Go back to your code, you get some undefined because of this line: 回到您的代码,由于此行,您得到了一些undefined代码:

// push to resultCount the counter for each word
resultCount[i] = counter;

The index i is the index of the current word in strArray . 索引istrArray当前单词的strArray You can fix it by removing this line, and do 您可以通过删除此行来修复它,然后执行

resultCount.push(counter)

After the end of the loop that starts with for (var j = i + 1; j < strArray.length; j++) . 在以for (var j = i + 1; j < strArray.length; j++)开始的循环结束之后。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何计算单词在数组中重复的次数? - How do I count the number of times a word is repeated in an array? 如何计算单词在字符串中的出现次数/将其存储在对象中? - How do I count the number of occurrences of a word in a string/store it in an object? 如何计算每个单词在文本文件中出现的次数 - How to count how many times each individual word appears in text file 如何使用javascript(在Greasemonkey脚本中)计算一个单词出现在网页中的次数? - How to count the number of times a word appears in a webpage using javascript (in a Greasemonkey script)? 在每次单击后重新加载页面时,如何计算按钮的单击次数? - How do I count the number of times the buttons click when the page reloads after each click? 计算文本字符串在使用Javascript的页面上出现的次数 - Count number of times a string of text appears on a page with Javascript 计算单个字母在一个单词中出现多少次 - Count how many times a single letter appears in a word 存储字母表中每个字母出现在所需位置的字符串中的次数 - Storing number of times each letter of the alphabet appears in a string in a desired location 我如何计算一个数组中的属性出现在另一个数组中的次数,以及 map 匹配新数组的次数? - How can I count and the number of times a property from one array appears in another, and map the matches to a new array? 计算字符串在另一个字符串中出现的次数 - count how many times a string appears within another string
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM