简体   繁体   中英

How to remove the delimiters from a csv file in ruby

I am reading a file which is either separated by a "tab space" or "semicolon(;)" or "comma(,)" below code separates only tab space but i want all 3 to be checked. like if a file is comma separated it should work for that also . Please help!

#!/usr/bin/ruby

require 'csv'

test = CSV.read('test.csv', headers:true, :col_sep => "\t") 
x = test.headers
puts x

It looks like :col_sep cannot be a Regexp, which could have solved your problem.

One possible solution would be to analyze the head of your CSV file and count the occurences of possible separators :

require 'csv'

possible_separators = ["\t", ';', ',']
lines_to_analyze = 1

File.open('test.csv') do |csv|
  head = csv.first(lines_to_analyze).join
  @col_sep = possible_separators.max_by { |sep| head.count(sep) }
end

@col_sep
#=> ";"

You can then use :

test = CSV.read('test.csv', headers:true, :col_sep => @col_sep) 
x = test.headers
puts x
# a
# b
# c

The values in x won't contain any separator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM