【问题标题】:Create a True Count to select most likely possible column创建一个真实计数以选择最有可能的列
【发布时间】:2020-02-08 21:24:56
【问题描述】:

我正在从 excel 文件中导入数据,并试图通过使用 RegEx 来定位具有我要查找的数据的列,从而从其相关列中定位某些信息。但是,正则表达式并不完美,因为有时表达式会出现在不止一列中。因此,为了解决这个问题,基本上我想制作某种内部计数器来计算一列具有我在集合中定义的正则表达式之一的次数。下面是一个发生这种情况的例子。

columnsWithDescription()
  {
    var refDesRegex = [/resistor/i,/capacitor/i,/res/i,/cap/i]

    var refDesColumnNumber = new Set();
    for (var expression of refDesRegex)
    {
      for (const row of this.data)
      {
        for (var cell = 0; cell<row.length; cell++)
        {
          if (expression.test(row[cell]))
          {
            refDesColumnNumber.add(cell)
          }
        }
      }
    }

data是已经导入的excel表格。它是一个数组数组,其中每个数组都是 Excel 工作表的一行。

我已经尝试在结果集上使用 forEach 方法,但这会产生总体真实计数,并且不会将结果与每个列号隔离开来。我想对集合的每个值运行测试,看看与单元格索引匹配的列中的值返回 true 的次数,然后隔离该行,以便稍后将其推送到数组中。

【问题讨论】:

  • 您还需要哪些信息?我已经解释了 this.data 是什么,并展示了我如何遍历数据以将值放入集合中
  • 1.你为什么不只使用一个正则表达式:/(resistor|capacitor|res|cap)/i? 2. 创建一个数组let counters = new Array(n).fill(0);,其中n 是电子表格中的最大列数,然后您的内部循环是if (expression.test(row[cell])) counters[cell]++;。您根本不需要 refDesColumnNumber 设置。
  • 我正在从提交给我的数据中识别数据 我无法控制这些数据的组织方式

标签: javascript regex excel angular typescript


【解决方案1】:

我想说的是:如果您有兴趣找出电子表格的哪一列与任何正则表达式的匹配度最高,那么:

  1. 您不必单独测试每个正则表达式。您可以针对一个正则表达式进行测试,该正则表达式是各个正则表达式的“逻辑或”。
  2. 您只需要为每个列编号记录该列与正则表达式(在字典中)匹配的次数。

最后,您需要根据值对该字典的键和值进行排序,然后与最大值关联的键就是您要查找的结果。

columnsWithDescription()
{
  let regex = /(resistor|capacitor|res|cap)/i;
  let counts = {}; // dictionary of counts
  for (let row of this.data)
  {
    for (var cell = 0; cell < row.length; cell++)
    {
      if (regex.test(row[cell]))
      {
        // we have a match in column # cell
        if (cell in counts)
          counts[cell]++; // not the first time we've had a match in this column
        else
          counts[cell] = 1;
      }
    }
  }

  /* the keys of the counts dictionary are the column numbers
     and the values are the number of times a match was found in that column
  */
  // sort the counts dictionary:
  // create the items array
  let items = Object.keys(counts).map(function(key) {
    return [parseInt(key), counts[key]]; // the keys are actually strings
  });
  // sort items array in descending order based on the values:
  items.sort(function(first, second) {
    return second[1] - first[1];
  });
  return items[0][0]; // this is the column number that had the most matches
}

【讨论】:

  • ahhhh 好的,我误解了你之前的评论,为此道歉
  • 这太棒了,我很欣赏使用 cmets 真正有助于理解
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多