首页 > 解决方案 > 在 Ruby 中用引号将数组的输出包装到 CSV 转换

问题描述

我想知道的是如何让程序末尾从数组传递到 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 

标签: rubycsvparsing

解决方案


您可以将: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"

推荐阅读