[英]Replacing text in one CSV column using FasterCSV
作為Ruby的新手,我試圖找出如何使用FasterCSV進行以下操作:打開CSV文件,按其標題選擇一列,在此列中僅將所有出現的字符串x替換為y,寫出新文件到STDOUT。 以下代碼幾乎可以正常工作:
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”(請參閱代碼中的注釋)。 為什么會這樣? 以及如何避免呢? 謝謝。
您可以在初始化行中進行一些更改,這將有所幫助。 更改:
csv = FCSV.read(filename, :headers => true, :return_headers => true, :encoding => 'u')
至:
csv = FCSV.read(filename, :headers => true, :encoding => 'u')
我正在使用CSV,這是FasterCSV,僅它是Ruby 1.9的一部分。 這將在當前目錄“ temp.csv”中創建一個帶有修改后的“ FName”字段的CSV文件:
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
可以直接在FasterCSV對象中操作所需的列,而不用創建一個新列,然后嘗試用新列替換舊列。
csv = FCSV.read(filename, :headers => true, :header_converters => :symbol, :return_headers => true, :encoding => 'u')
mycol = csv[:my_col]
mycol.each do |row|
row.gsub!(/\s*;\s*/,"///") unless row.nil? # or any other substitution
csv.each do |r|
puts r.to_csv(:force_quotes => true)
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.