所以我想做的是从现有的 CSV 文件中读取特定的列,从提取的数据中解析一些信息,然后在单个列中使用新解析的信息创建一个新的 CSV 文件。生成的数组的标题和第一个条目正确地进入 CSV 文件,但在这些之后,每个其他条目进入同一行的相邻单元格而不是创建一列,所以它就像一个 L 形而不只是一条线。有什么想法吗?
#!ruby.exe
require 'csv'
puts "Please enter a file name:" #user input file name (must be in same
folder as this file)
file = gets.chomp
begin
File.open(file, 'r')
rescue
print "Failed to open #{file}\n"
exit
end #makes sure that the file exists, if it does not it posts an error
data_file = File.new(file)
data = [] #initializes array for addresses from .csv
counter=0 #set counter up to allow for different sized files to be used
without issue
CSV.foreach(data_file, headers: true) do |row|
data << row.to_hash
counter+=1
end #goes through .csv one line ar a time
data.reject(&:empty?)
puts "Which column do you want to parse?"
column = gets.chomp
i=0
streets = []
while (i<counter)
address = data[i][column]
street_name = address.gsub(/^((\d[a-zA-Z])|[^a-zA-Z])*/, '')
streets.push(street_name)
i+=1
end
streets.reject(&:empty?)
puts "What do you want the output to be called?"
new_file = gets.chomp
CSV.open(new_file, "w", :write_headers=> true, :headers => [column]) do |hdr|
hdr << streets
end
最佳答案
您应该扫描街道数组并将其作为一行插入,这意味着您需要在发送到 csv 之前将数据行放入数组中。好吧,也许代码比解释更简单:
CSV.open(new_file, "w", :write_headers=> true, :headers => [column]) do |csv_line|
streets.each { |street| csv_line << [street] }
end
关于ruby - 如何在 CSV 文件中生成列而不是行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51443525/