【问题标题】:trying to find the 1st instance of a string in a CSV using fastercsv尝试使用 fastercsv 在 CSV 中查找字符串的第一个实例
【发布时间】:2011-08-23 04:42:29
【问题描述】:

我正在尝试打开一个 CSV 文件,查找一个字符串,然后返回 csv 文件的第二列,但只返回它的第一个实例。我已经做到了以下几点,但不幸的是,它返回了每个实例。我有点不知所措。

鲁比之神能帮忙吗?非常感谢。

M

就本示例而言,假设 names.csv 是一个包含以下内容的文件:

foo, happy
foo, sad
bar, tired
foo, hungry
foo, bad


#!/usr/local/bin/ruby -w

require 'rubygems'
require 'fastercsv'
require 'pp'

  FasterCSV.open('newfile.csv', 'w') do |output|
    FasterCSV.foreach('names.csv') do |lookup|
      index_PL = lookup.index('foo')
      if index_PL
        output << lookup[2]
      end
    end
  end

好的,所以,如果我想返回 foo 的所有实例,但在 csv 中,那么它是如何工作的? 所以我想要的结果是快乐、悲伤、饥饿、糟糕。我以为会是:

  FasterCSV.open('newfile.csv', 'w') do |output|
    FasterCSV.foreach('names.csv') do |lookup|
      index_PL = lookup.index('foo')
      if index_PL
        build_str << "," << lookup[2]
      end
      output << build_str
    end
  end

但它似乎不起作用

【问题讨论】:

  • 您考虑过只使用grepcut 吗?例如grep 'foo' | cut -d, -f2
  • 'foo' 是改变还是静态的?,你能粘贴一个 names.csv 的示例 sn-p
  • 是的,已经考虑过 grep + cut 但它是更大程序的一部分。此外, foo 确实会被一个不断变化的变量替换,但出于此目的,我们可以假设它只是字符串 foo。 (谢谢)

标签: ruby csv fastercsv


【解决方案1】:

foreach 替换为open(以获得可枚举)和find

FasterCSV.open('newfile.csv', 'w') do |output|
    output << FasterCSV.open('names.csv').find { |r| r.index('foo') }[2]
end

如果没有找到任何东西,index 调用将返回 nil;这意味着find 将为您提供具有'foo' 的第一行,您可以从结果中提取索引2 处的列。

如果您不确定names.csv 是否有您要查找的内容,则建议进行一些错误检查:

FasterCSV.open('newfile.csv', 'w') do |output|
    foos_row = FasterCSV.open('names.csv').find { |r| r.index('foo') }
    if(foos_row)
        output << foos_row[2]
    else
        # complain or something
    end
end

或者,如果您想默默地忽略缺少 'foo' 并使用空字符串,您可以执行以下操作:

FasterCSV.open('newfile.csv', 'w') do |output|
    output << (FasterCSV.open('names.csv').find { |r| r.index('foo') } || ['','',''])[2]
end

不过,我可能会选择“如果找不到就投诉”的版本。

【讨论】:

  • 嗯,真的很有趣,解释也很有帮助。如果我想返回第一个实例以外的东西怎么办?我的理解是 .index 只返回第一个实例,所以如果我想要第二个/第三个/任何实例,它会在哪里改变?再次感谢。
  • @MarkL: index 只是用于查看该行是否有'foo',您可以使用任何合适的测试。如果你想要所有匹配的行,那么有find_all
  • 好的,所以 .index 返回一个 foo 实例,而 find_all 返回所有 foo 实例?我原以为 .index 再次返回了 foo 的第一个实例(因此造成混乱)thx。
  • @MarkL: 不,index 找到您要查找的索引或nil 如果它不存在。 find 返回迭代器的第一个值,其中块返回真值。
猜你喜欢
  • 2019-04-24
  • 2017-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多