简体   繁体   English

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

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

A bit of a noob here so apologies in advance. 这里有点菜鸟,所以提前道歉。

I am trying to read a CSV file which has a number of columns, I would like see if one string "foo" exists anywhere in the file, and if so, grab the string one cell over (aka same row, one column over) and then write that to a file 我正在尝试读取具有多个列的CSV文件,我想查看文件中是否存在一个字符串“ foo”,如果是,则将该字符串抓到一个单元格上(即同一行,一列上)然后将其写入文件

my file c.csv: 我的文件c.csv:

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

so in this case, I would want "bar" and "tom" in a new csv file. 因此在这种情况下,我希望在新的csv文件中使用“ bar”和“ tom”。

Here's what I have so far: 这是我到目前为止的内容:

#!/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

I've looked here https://github.com/circle/fastercsv/blob/master/examples/csv_table.rb but I am obviously not understanding it, my best guess is that I'd have to use Table to do what I want to do but after banging my head up against the wall for a bit, I decided to ask for advice from the experienced folks. 我看过这里https://github.com/circle/fastercsv/blob/master/examples/csv_table.rb,但我显然不明白,我的最佳猜测是我必须使用Table来做我想做的事情我想做,但是在将我的头撞到墙上一会儿之后,我决定向经验丰富的人寻求建议。 help please? 请帮助?

Given your input file c.csv 给定您的输入文件c.csv

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

then this script: 然后这个脚本:

#!/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

will create the file output.csv 将创建文件output.csv

bar
tom

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

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