ruby - 在 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
解决方案
您可以将: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"
推荐阅读
- node.js - tsconfig 在节点 14 的 vscode 中启用智能感知
- javascript - 超出范围的函数调用
- google-apps-script - 如何为通过 Google 脚本创建的自动填充中添加的每个公式创建 2 秒的暂停?
- angular - 如何在标签内的同一个 *ngIf 上设置多个条件?
- c# - 在c#中设置基类的属性
- apache-kafka - 如何将kafka消息下载到文件中
- apache-spark - 如何在 pyspark 中删除常量列,但不删除具有空值和另一个值的列?
- r - 如何根据字符(小于号“<”)的出现重新计算数据框中的值?
- react-native - 组件异常:组件的视图配置 getter 回调必须是函数(收到“未定义”)
- python - Top2Vec 错误 - 'KeyedVectors' 对象没有属性 'vectors_docs'