将数组的输出以Ruby中的引号包装为CSV转换

时间:2018-07-20 20:05:09

标签: ruby csv parsing

我想找出的是如何使程序末尾从数组传递到CSV的每个条目都用“”包裹,以允许Excel正确读取它。我知道这需要在第34行的“推送”之前或期间完成,但是执行“ streets.push('“'+ street_name +'”'))“会导致每个条目都被三个引号引起来,但这并不是对我来说很有意义。

#!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 

2 个答案:

答案 0 :(得分:2)

您可以将:force_quotes选项传递给CSV库,以使其引用csv中的所有内容:

base_options = {headers: ['first,col', 'second column'], write_headers: true}
options = [{}, {force_quotes: true}]

data = [
  ['a', 'b'],
  ['c', 'd'],
  ['e', 'f']
]

options.each do |option|
  result = CSV.generate(base_options.merge(option)) do |csv|
    data.each do |datum|
      csv << datum
    end
  end

  puts "#{option}:\n#{result}"
end

例如,在此小脚本中,默认情况下,唯一被引用的是第一列标题,因为它包含逗号。通过传入force_quotes: true,尽管在第二遍,所有内容都被引用了。

输出:

{}:
"first,col",second column
a,b
c,d
e,f
{:force_quotes=>true}:
"first,col","second column"
"a","b"
"c","d"
"e","f"

答案 1 :(得分:1)

您可以使用map处理数组,然后再将其放入csv。

   streets.map!{|s| '"'+s+'"'}