繁体   English   中英

试图使用FasterCSV获取列之间的差异

[英]trying to get the delta between columns using FasterCSV

这里有点菜鸟,所以提前道歉。

我正在尝试读取具有多个列的CSV文件,我想查看文件中是否存在一个字符串“ foo”,如果是,则将该字符串抓到一个单元格上(即同一行,一列上)然后将其写入文件

我的文件c.csv:

foo,bar,yip
12,apple,yap
23,orange,yop
foo,tom,yum

因此在这种情况下,我希望在新的csv文件中使用“ bar”和“ tom”。

这是我到目前为止的内容:

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

require 'rubygems'
require 'fastercsv'

rows = FasterCSV.read("c.csv")
acolumn = rows.collect{|row| row[0]}

if acolumn.select{|v| v =~ /foo/} == 1
i = 0
for z in i..(acolumn).count
puts rows[1][i]
end

我看过这里https://github.com/circle/fastercsv/blob/master/examples/csv_table.rb,但我显然不明白,我的最佳猜测是我必须使用Table来做我想做的事情我想做,但是在将我的头撞到墙上一会儿之后,我决定向经验丰富的人寻求建议。 请帮助?

给定您的输入文件c.csv

foo,bar,yip
12,apple,yap
23,orange,yop
foo,tom,yum

然后这个脚本:

#!/usr/bin/ruby1.8

require 'fastercsv'

FasterCSV.open('output.csv', 'w') do |output|
  FasterCSV.foreach('c.csv') do |row|
    foo_index = row.index('foo')
    if foo_index
      value_to_the_right_of_foo = row[foo_index + 1]
      output << value_to_the_right_of_foo
    end
  end
end

将创建文件output.csv

bar
tom

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM