我有一个CSV对象,内容如下:
I got an object of CSV, the content is like:
full_name | phone_number | Mike Smith | (123)-456-7890| Tony Davis | (213)-564-7890|我想将"full_name"列分为两列,分别代表"first_name"和"last_name":
And I would like to split the column of 'full_name' into two columns, which represents 'first_name' and 'last_name':
first_name | last_name | phone_number | Mike | Smith | (123)-456-7890| Tony | Davis | (213)-564-7890|我没有找到执行该命令的命令,如何拆分它?非常感谢你!
I didn't find a command to do it, how can I split it? Thank you very much!
此部分的代码为:
def to_csv(options = {}) CSV.generate(options) do |csv| columns = %w[ full_name phone_number ] csv << columns each do |books| csv << columns.map { |column| books.public_send(column) } .map { |column| ActionController::Base.helpers.strip_tags(column.to_s) } end end end此方法的调用者:
send_data(books.to_csv(col_sep: ','),filename: 'booksAuthorsInfo.csv',type: 'application/csv')"books"的类类型为ActiveRecord_AssociationRelation,我不知道如何将full_name列拆分为两列,这似乎对String.split没有帮助.
The class type of 'books' is ActiveRecord_AssociationRelation, and I don't know how to split that full_name column into two columns, it looks like the String.split is not helpful.
推荐答案到目前为止,这个问题还没有足够的道理,因此我希望它最终将被关闭.这是有关如何拆分字段的一些信息,以便我们可以找到问题的真正根源.
So far the question doesn't make enough sense so I expect it'll be closed eventually. Here's some information about how to split the fields so that, maybe, we can get to the real root of the problem.
对此进行冥想:
ary = <<EOT full_name | phone_number | Mike Smith | (123)-456-7890| Tony Davis | (213)-564-7890| EOT PIPE_DELIMITER = /\s*\|\s*/ munged_data = ary.lines[1..-1].map { |l| full_name, phone_number = l.split(PIPE_DELIMITER) # => ["Mike Smith", "(123)-456-7890"], ["Tony Davis", "(213)-564-7890"] first_name, last_name = full_name.split # => ["Mike", "Smith"], ["Tony", "Davis"] [first_name, last_name, phone_number] } # => [["Mike", "Smith", "(123)-456-7890"], ["Tony", "Davis", "(213)-564-7890"]]此时,可以生成一些可用的CSV数据:
At this point it's possible to generate some usable CSV data:
require 'csv' CSV.open("/dev/stdout", "wb") do |csv| csv << %w[first_name last_name phone_number] munged_data.each do |row| csv << row end end这将导致:
# >> first_name,last_name,phone_number # >> Mike,Smith,(123)-456-7890 # >> Tony,Davis,(213)-564-7890请注意使用正则表达式作为split的参数;这告诉split通过仅分割由|分隔的零个或多个空格来清除输出结果:
Note the use of a regular expression as a parameter to split; This tells split to clean up the resulting output a bit by only splitting on zero-or-more whitespace delimited by |:
PIPE_DELIMITER = /\s*\|\s*/ full_name, phone_number = l.split('|') # => ["Mike Smith ", " (123)-456-7890", "\n"], ["Tony Davis ", " (213)-564-7890", "\n"] full_name, phone_number = l.split(PIPE_DELIMITER) # => ["Mike Smith", "(123)-456-7890"], ["Tony Davis", "(213)-564-7890"]此时,很容易拆分名称:
At that point it is easy to split the names:
first_name, last_name = full_name.split # => ["Mike", "Smith"], ["Tony", "Davis"]更多推荐
如何在Ruby中将一列的内容分为csv的两列?
发布评论