簡體   English   中英

如何計算每個單詞在字符串中出現的次數?

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

我現在正在學習JavaScript,並且正在開發一個函數,該函數將計算單詞在字符串中出現的次數,然后將答案作為對象吐出來。 根據該站點上類似線程的一些建議,我決定使用.split和一個計數器函數來制作二維數組,然后使用結果填充對象。 當我遇到某些字符串問題時,我正在用示例文本運行測試。 我不知道為什么某些計數器顯示為未定義。

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 ); 

我發現在示例中使用單詞“ this”和“ is”時,我經常返回“ undefined”作為這些單詞的單詞計數。 例如,“成為或不成為”將為“那個”和“是”返回“未定義”。 有人可以幫助闡明這里發生了什么嗎? 謝謝。

您的代碼不可讀:

  • 太長的代碼塊
  • 非信息性的變量名(例如answer

其次,您的算法非常慢:您可以通過僅解析整個數組一次來計數單詞。

最后但並非最不重要的一點是,您應該在循環外部創建answer數組。

這是使用現代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
}

在較舊的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
}

回到您的代碼,由於此行,您得到了一些undefined代碼:

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

索引istrArray當前單詞的strArray 您可以通過刪除此行來修復它,然后執行

resultCount.push(counter)

在以for (var j = i + 1; j < strArray.length; j++)開始的循環結束之后。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM