【问题标题】:Ruby CSV parsing Count Column HeadersRuby CSV解析计数列标题
【发布时间】:2017-05-26 01:20:15
【问题描述】:

我有这个 CSV 文件:

col1,  col2,     col3,     col4, col5
name1, contact1, addr, ess1, zip1, comment1    <==
name2, contact2, address2, zip2, comment2
name3, contact3, address3, zip3, comment3

当我数列时:

columns = CSV.read(file_path, headers: true).headers

当第二行(第 1 条记录/行)的列数超过列标题数时,这将返回更大的数字:6

打印的标题:col1, col2, col3, col4, col5, nil

我想正确计算 CSV 列标题,以将其与每条记录/行的列数进行比较。

columns = CSV.read(file_path, headers: true).headers
logger.info("COLUMN NAMES: #{columns.inspect}")
logger.info("COLUMN COUNT: #{columns.count}")

CSV.foreach(file_path, option) do |row|
  # Check if a row columns matches file column headers count
  if row.count != columns.count
    logger.info("Error: Row count not match.")
    File.delete(lock_file)
    exit
  end
end

我想在保存记录之前将COLUMN HEADERS COUNTRECORD COLUMNS COUNT 匹配。如果记录的列多于标题,则记录中可能会出现逗号,

这也可能意味着用户提供了无效的记录数据,并且记录列将不匹配 DB 表上的每个字段。

【问题讨论】:

  • 大概算一下第一行有多少nil
  • @c650 我敢打赌第一行没有nil,因为它超过了列标题的数量。标题:5 |行列:6
  • 如果您解释为什么要这样做,它可能会帮助我们回答您。这听起来有点像“XY Problem”。
  • @theTinMan 感谢您指出这一点。我更新了问题并添加了 EDIT 部分为什么我需要它来工作。

标签: ruby-on-rails ruby csv


【解决方案1】:

只要您在任何其他行中有额外的列,您将始终在标题中获得 nil,因此,由于您在第一行中有 6 列,因此您会得到:

col1, col2, col3, col4, col5, nil

一种解决方案是删除在headers 数组末尾找到的所有nil 值,如下所示:

columns = CSV.read(file_path, headers: true).headers
columns.pop while columns.last.nil?

# ...

现在,在您的示例中,您将获得以下标题:

col1, col2, col3, col4, col5

计数将是5,因此您的代码现在应该可以按预期工作了。

【讨论】:

  • 这似乎是一个非常干净的想法。感谢您的帮助!
猜你喜欢
  • 2012-06-08
  • 2014-02-07
  • 1970-01-01
  • 2013-08-24
  • 1970-01-01
  • 2012-06-28
  • 2013-12-04
  • 1970-01-01
  • 2017-05-25
相关资源
最近更新 更多