我该如何使用Google表格中的脚本计算这些单词?

问题描述 投票:0回答:1

我想计算一个字符串中一个单词的出现次数,但是Google表格给我一个错误,它不能处理表达式:

finalScores.push(preOutputTxt.match(nameArr[x])).length);   

因为某处没有null。我怎样才能解决这个问题?完整代码:

/**
*   
*   
* 
* @customFunction
*/

function scoreCounting(scores, names){
  //---variables---//
  var scoresArr = [];
  var preOutputTxt = "";
  var finalScores = [];
  var nameArr = [];
  //---------------//


  //---creating an array from names and scores (scores are in string type)---//
  for(var w = 0; w < scores.length; w ++){
    scoresArr.push(scores[w]);
  }
  for(var z = 0; z < names.length; z++){
    nameArr.push(names[z]);
  }
  //---------------------------------------//


  //---make one big string with names---//
  for(var y = 0; y < scoresArr.length; y++){
   preOutputTxt += scoresArr[y];
  }
  //----------------------------------------------//


  //---counting how many times score (a name) occur, basing on name given by nameArr[]---//
  for(var x = 0; x < nameArr.length; x++){ 
    finalScores.push(preOutputTxt.match(nameArr[x])).length); 
  }

  return finalScores;
}
javascript google-sheets formula counting
1个回答
0
投票

正如Tedinoz所述,如果您可以共享电子表格,则提供特定帮助会更容易。

但是与此同时,这里有两个片段帮助说明了如何获取较长字符串中的单词计数。

示例1:如果使用match()作为名称输入,则只会得到第一个匹配项。

[这是因为该方法需要正则表达式。并且传递字符串(或设置为字符串的变量)类似于不带修饰符的正则表达式。]

function example1() {
  var preOutputTxt = 'abcabcabc';
  var name  = 'abc';
  var output = preOutputTxt.match(name);
  Logger.log('Output is %s. Length is %s.', output, output.length);
}

// Output is [abc]. Length is 1.0.

示例2:但是,如果您使用带有全局修饰符的正则表达式,则会获得所有匹配项。

function example2() {
  var preOutputTxt = 'abcabcabc';
  var name  = 'abc';
  var re = new RegExp(name, 'g');
  Logger.log('Regular expression is %s', re);
  var output = preOutputTxt.match(re);
  Logger.log('Output is %s. Length is %s.', output, output.length);
}

// Regular expression is /abc/g
// Output is [abc, abc, abc]. Length is 3.0.
© www.soinside.com 2019 - 2024. All rights reserved.