我正在學習 ruby??,但我遇到了這個問題:我遇到了. CSV通過. Text檔案寫入的問題。這是我的 Ruby 代碼:
require 'csv'
class Plantas <
Struct.new(:identifier, :code, :lang, :fullname)
end
f = File.open("planta.txt", "r")
f.each_line { |line|
fields = line.split(',')
newPlant = Plantas.new
newPlant.identifier = fields[0].tr_s('"', '').strip
newPlant.code = fields[2].tr_s('"', '').strip
newPlant.lang = fields[3].tr_s('"', '').strip
newPlant.fullname = fields[10].tr_s('"', '').strip
str = "#{newPlant.identifier} #{newPlant.code} #{newPlant.lang} #{newPlant.fullname}" #linies a imprimir
#puts str
CSV.open("plantas.csv", "w") do |csv|
csv << [str]
end
}
這就是我的.txt檔案:
"identifier","datatype","code","lang","langno","preferred","status","creation","modification","country","fullname","authority","shortname"
"N1952","PFL","LEECO","la","1","0","N","06/06/2000","09/03/2010","","Leea coccinea non","Planchon","Leea coccinea non"
"N51170","PFL","CAWUR","en","4","0","N","28/02/2002","24/08/2010","","Toddy palm","","Toddy palm"
這就是輸出 .csv
N51170 CAWUR en Toddy palm
只寫最后一行而不是.txt
我希望代碼列印 file.csv 中的所有行而不是所有行,而不是'"'和','
有人可以幫忙嗎?謝謝!
uj5u.com熱心網友回復:
你非常接近!
鑒于:
% cat file.csv
"identifier","datatype","code","lang","langno","preferred","status","creation","modification","country","fullname","authority","shortname"
"N1952","PFL","LEECO","la","1","0","N","06/06/2000","09/03/2010","","Leea coccinea non","Planchon","Leea coccinea non"
"N51170","PFL","CAWUR","en","4","0","N","28/02/2002","24/08/2010","","Toddy palm","","Toddy palm"
您可以通過以下方式修改代碼:
require 'csv'
class Plantas <
Struct.new(:identifier, :code, :lang, :fullname)
end
f_in = File.open("/tmp/file.csv", "r")
f_out=CSV.open("/tmp/plantas.csv", "w")
f_in.each_line { |line|
fields = line.split(',')
newPlant = Plantas.new
newPlant.identifier = fields[0].tr_s('"', '').strip
newPlant.code = fields[2].tr_s('"', '').strip
newPlant.lang = fields[3].tr_s('"', '').strip
newPlant.fullname = fields[10].tr_s('"', '').strip
str = "#{newPlant.identifier} #{newPlant.code} #{newPlant.lang} #{newPlant.fullname}" #linies a imprimir
f_out << [str]
}
結果如下:
% cat plantas.csv
identifier code lang fullname
N1952 LEECO la Leea coccinea non
N51170 CAWUR en Toddy palm
更好的是,您可以正確地將輸入視為 CSV 讀取它:
# same top part, then:
f_in = CSV.open("/tmp/file.csv", "r")
f_out=CSV.open("/tmp/plantas.csv", "w")
f_in.each { |row|
newPlant = Plantas.new
newPlant.identifier = row[0]
newPlant.code = row[2]
newPlant.lang = row[3]
newPlant.fullname = row[10]
str = "#{newPlant.identifier} #{newPlant.code} #{newPlant.lang} #{newPlant.fullname}" #linies a imprimir
puts str
f_out << [str]
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/360601.html
上一篇:生成CSV,一列內的數字陣列
