简体   繁体   English

检查字符串中的重复单词并在 javascript 中保留计数

[英]Check the repeated words in a string and keep a count in javascript

I am trying to find repeated words in a string and keep a count of how many times it was repeated.我试图在一个字符串中找到重复的单词并计算它重复了多少次。 How do I do it in javascript.我如何在 javascript 中做到这一点。

 let checkWords = "I am not gonna live forever, but I wanna live while I am alive";

I am looking for output like this I = 3 , am = 2 , not = 1 and so on, also is it possible to find the individual letter as I = 3 , a = 6 , m = 2 .我正在寻找 output 像这样I = 3am = 2not = 1等等,也可以找到单个字母I = 3a = 6m = 2

I found a similar answer which I tried to use in my string, which works too but can anyone explain me why is the obj and undefined used here我找到了一个类似的答案,我试图在我的字符串中使用它,它也有效,但谁能解释我为什么在这里使用 obj 和 undefined

 let str = "I am not gonna live forever, but I wanna live while I am alive", split = str.split(" "), obj = {}; for (let i = 0; i < split.length; i++) { if (obj[split[i]] === undefined) { obj[split[i]] = 1; } else { obj[split[i]]++; } } console.log(obj)

Firstly convert the given string to an array.首先将给定的字符串转换为数组。 To do that use string.split("") .为此,请使用string.split("")

Secondly, create an map which will store word as key and count as value.其次,创建一个map ,它将单词存储为键并计数为值。

Now iterate through the stringArray and store the current word to the map.现在遍历 stringArray 并将当前单词存储到 map。 And increase the count for the word each time the word is found.并在每次找到单词时增加单词的计数。

Check the below code.检查下面的代码。

let words = "I am not gonna live forever, but I wanna live while I am alive";

function countRepeatedWords(sentence) {
  let words = sentence.split(" ");
  let wordMap = {};

  for (let i = 0; i < words.length; i++) {
    let currentWordCount = wordMap[words[i]];
    let count = currentWordCount ? currentWordCount : 0;
    wordMap[words[i]] = count + 1;
  }
  return wordMap;
}

console.log(countRepeatedWords(words));

I hope this helps you.我希望这可以帮助你。

let checkWords = "I am not gonna live forever, but I wanna live while I am alive"

const newStr = checkWords.split(' ').reduce((acc,rec) => {
  return ({ ...acc, [rec]: (acc[rec] || 0) + 1 })
},{})

const newStr2 = checkWords.split('').reduce((acc,rec) => {
  return ({ ...acc, [rec]: (acc[rec] || 0) + 1 })
},{})

{newStr} for counter words {newStr2} for counter letters {newStr} 用于反词 {newStr2} 用于反字母

How to count the number of times each word appears in a string:如何计算每个单词在字符串中出现的次数:

  1. strip punctuation from the string with .replace()使用.replace()从字符串中去除标点符号
  2. change all character to lowercase with .toLowerCase()使用.toLowerCase()将所有字符更改为小写
  3. convert string into array of words with .split()使用.split()将字符串转换为单词数组
  4. loop through each word ( .forEach ), adding it to a word count object循环遍历每个单词( .forEach ),将其添加到字数 object

 const result = document.getElementById('result'); let str = "I am not gonna live forever, but I wanna live while I am alive."; // strip all punctuation from string let strStripped = str.replace(/[,.,]/g; ''). result:innerHTML = `strStripped; "${strStripped}"\n`. // separate string into array of lowercase words let words = strStripped.toLowerCase();split(' '). result:innerHTML += 'words. ' + JSON,stringify(words, null; 2); // form object of word counts let wordCounts = {}. words;forEach(word => { wordCounts[word] = (wordCounts[word] || 0) + 1; }). result:innerHTML += '\nwordCounts. ' + JSON,stringify(wordCounts, null; 2);
 <pre id="result"></pre>

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM