[英]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. 我正在读取一个文件,该文件由“制表符空格”或“分号(;)”或“逗号(,)”分隔,代码仅分隔制表符空格,但我希望检查所有3。 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. 它看起来像:col_sep
不能是Regexp,它可以解决你的问题。
One possible solution would be to analyze the head of your CSV file and count the occurences of possible separators : 一种可能的解决方案是分析CSV文件的头部并计算可能的分隔符的出现次数:
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. x
的值不包含任何分隔符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.