【问题标题】:Wrapping output of an array to CSV conversion in quotations in Ruby在 Ruby 中用引号将数组的输出包装到 CSV 转换
【发布时间】:2018-12-29 04:25:57
【问题描述】:

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

【问题讨论】:

    标签: ruby csv parsing


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      您可以在将数组放入 csv 之前使用 map 对其进行处理。

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

      【讨论】:

        猜你喜欢
        • 2011-06-16
        • 2020-12-22
        • 2014-08-21
        • 2014-03-31
        • 1970-01-01
        • 2011-11-25
        • 1970-01-01
        • 2016-12-05
        • 1970-01-01
        相关资源
        最近更新 更多