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