2010-12-13 59 views
0

对于Ruby来说相对较新,我试图弄清楚如何使用FasterCSV执行以下操作:打开一个CSV文件,在其列表中选择一个列,在此列中只替换全部字符串x与y的出现,将新文件写出到STDOUT。 下面的代码几乎工作:使用FasterCSV替换一个CSV列中的文本

filename = ARGV[0] 
csv = FCSV.read(filename, :headers => true, :header_converters => :symbol, :return_headers => true, :encoding => 'u') 
mycol = csv[:mycol] 
# construct a mycol_new by iterating over mycol and doing some string replacement 
puts csv[:mycol][0] # produces "MyCol" as expected 
puts mycol_new[0] # produces "MyCol" as expected 
csv[:mycol] = mycol_new 
puts csv[:mycol][0] # produces "mycol" while "MyCol" is expected 
csv.each do |r| 
    puts r.to_csv(:force_quotes => true) 
end 

唯一的问题是,有一个标题变换,我不希望它。如果在替换csv表中的列之前所选列的标题为“MyCol”,则之后为“mycol”(请参阅​​代码中的注释)。为什么会发生?以及如何避免它?谢谢。

回答

4

在初始化行中有几件事可以改变,这将有所帮助。更改:

csv = FCSV.read(filename, :headers => true, :return_headers => true, :encoding => 'u') 

到:

csv = FCSV.read(filename, :headers => true, :encoding => 'u') 

我使用的CSV,这是FasterCSV只有它的Ruby 1.9的一部分。这将创建在当前目录中的CSV文件名为“temp.csv”有修改的“FName参数”字段:

require 'csv' 

data = "ID,FName,LName\n1,mickey,mouse\n2,minnie,mouse\n3,donald,duck\n" 

# read and parse the data 
csv_in = CSV.new(data, :headers => true) 

# open the temp file 
CSV.open('./temp.csv', 'w') do |csv_out| 

    # output the headers embedded in the object, then rewind to the start of the list 
    csv_out << csv_in.first.headers 
    csv_in.rewind 

    # loop over the rows 
    csv_in.each do |row| 

    # munge the first name 
    if (row['FName']['mi']) 
     row['FName'] = row['FName'][1 .. -1] << '-' << row['FName'][0] << 'ay' 
    end 

    # output the record 
    csv_out << row.fields 
    end 
end 

输出看起来像:

ID,FName,LName 
1,ickey-may,mouse 
2,innie-may,mouse 
3,donald,duck 
+0

谢谢Greg。当你编写有用的东西时,直接操纵选择列而不是构建新列,然后尝试用新列替换现有列(请参见下面的代码)。 – Stefan 2010-12-17 08:12:19

3

它是可以操纵所需列直接在FasterCSV对象中,而不是创建新列,然后尝试用新的列替换旧列。