2013-05-02 146 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