如何在CSV文件中生成列而不是行

时间:2018-07-20 13:22:45

标签: ruby csv spreadsheet

因此,我要做的是从现有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 

1 个答案:

答案 0 :(得分:1)

您应该扫描街道数组并将其作为行插入,这意味着您需要先将数据行放入数组中,然后才能发送到csv。好的,也许代码比解释要简单:

CSV.open(new_file, "w", :write_headers=> true, :headers => [column]) do |csv_line|
  streets.each { |street| csv_line << [street] }
end