2013-05-02 148 views
-1

我读取CSV文件时出现问题,两列由“\ tab”分隔。如何读取CSV文件?

我的代码是:

require 'csv' 
require 'rubygems' 

# Globals 
INFINITY = 1.0/0 

if __FILE__ == $0 
    # Locals 
    data = [] 
    fn = '' 

    # Argument check 
    if ARGV.length == 1 
    fn = ARGV[0] 
    else 
    puts 'Usage: kmeans.rb INPUT-FILE' 
    exit 
    end 

    # Get all data 
    CSV.foreach(fn) do |row| 
    x = row[0].to_f 
    y = row[1].to_f 

    p = Point.new(x,y) 
    data.push p 
    end 

    # Determine the number of clusters to find 
    puts 'Number of clusters to find:' 
    k = STDIN.gets.chomp!.to_i 

    # Run algorithm on data 
    clusters = kmeans(data, k) 

    # Graph output by running gnuplot pipe 
    Gnuplot.open do |gp| 
    # Start a new plot 
    Gnuplot::Plot.new(gp) do |plot| 
     plot.title fn 

     # Plot each cluster's points 
     clusters.each do |cluster| 
     # Collect all x and y coords for this cluster 
     x = cluster.points.collect {|p| p.x } 
     y = cluster.points.collect {|p| p.y } 

     # Plot w/o a title (clutters things up) 
     plot.data << Gnuplot::DataSet.new([x,y]) do |ds| 
      ds.notitle 
     end 
     end 
    end 
    end 
end 

的文件是:

48.2641334571 86.4516903905 
0.1140042627 35.8368597414 
97.4319168245 92.8009240744 
24.4614031388 18.3292584382 
36.2367675367 32.8294024271 
75.5836860736 68.30729977 
38.6577034445 25.7701728584 
28.2607136287 64.4493377817 
61.5358486771 61.2195232194 

我得到这个错误:

test.csv:1: syntax error, unexpected ',', expecting $end 
48.2641334571,86.4516903905 
      ^
+0

在第一行中提到的fn是什么? – Yossi 2013-05-02 18:25:32

+0

添加了代码,它是文件描述符 – 2013-05-02 18:27:10

+2

在底部缺少结尾 – fotanus 2013-05-02 18:27:32

回答

3

你只是缺少一个end在底部。您的第一个if未关闭。

CSV是“逗号分隔值”。你正在使用标签。这不是一个大问题,因为CSV类可以处理它,你只需要指定你的分隔符是制表:

CSV.foreach(fn, { :col_sep => "\t" }) 

请务必仔细检查您的文件,它使用的标签,而不是空格这是不一样的。

我仍然对错误信息感到困惑,这是你收到的一切吗?

+0

是的,结束了,但错误仍然存​​在。 :S – 2013-05-02 18:34:23

+0

您是否可以使用更新后的来源和错误消息更新您的问题。这可以帮助我们帮助你。 – Martin 2013-05-02 18:53:21

+0

done ...谢谢:p – 2013-05-02 19:06:40