如何读取CSV文件?

时间:2013-05-02 18:22:48

标签: ruby csv file-io

我在阅读包含两列用“\ 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
              ^

1 个答案:

答案 0 :(得分:3)

您在底部错过了end。您的第一个if未关闭。

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

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

请务必仔细检查您的文件是否正在使用标签,而不是使用不同的空格。

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