-1

我在读取包含由“\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
              ^
4

1 回答 1

3

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

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

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

请务必仔细检查您的文件是否使用制表符,而不是不同的空格。

我仍然对错误消息感到困惑,这是您收到的所有内容吗?

于 2013-05-02T18:31:18.473 回答