首页 > 解决方案 > 我如何计算这些单词,使用谷歌表格中的脚本?

问题描述

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

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

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

/**
*   
*   
* 
* @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;
}

标签: javascriptgoogle-sheetsformulacounting

解决方案


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

但与此同时,这里有两个片段有助于解释如何在较长的字符串中获取单词的计数。

示例 1:如果您使用match()name 作为输入,您将只获得第一个匹配项。

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

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.

推荐阅读