-1

这对我很有用。

lines = CSV.readlines("log.csv")
a = lines.map{|s| {timestamp: s[0], url: s[1], ip: s[3]} }
puts a

修改为更清晰。

lines = CSV.readlines("log.csv").map do |s|
  s = {timestamp: s[0], url: s[1], ip: s[3]}
end
puts a

但是我正在考虑使用 grep 进行额外的过滤,这非常失败。

1.9.3-p448 :129 > lines = File.readlines("log.csv").grep(/watch\?v=/)
 => [] 
1.9.3-p448 :134 > lines.map{|s| {timestamp: s[0], url: s[1], ip: s[3]} }
=> [{:timestamp=>"\"", :url=>"2", :ip=>" "}, {:timestamp=>"\"", :url=>"2", :ip=>" "}

解决方案

a = File.readlines('log.csv').grep(/watch\?v=/).map do |s|
  s = s.parse_csv;
  { timestamp: s[0], url: s[1], ip: s[3] }
end
puts a

谢谢。

4

1 回答 1

2

该类CSVparse_csv方法添加到String. 所以你可以像这样一次解析一个文件记录

lines = File.readlines("log.csv").grep(/watch\?v=/)
a = lines.map{ |s| s = s.parse_csv; {timestamp: s[0], url: s[1], ip: s[3]} }
puts a

或者,最好是

a = File.readlines('log.csv').grep(/watch\?v=/).map do |s|
  s = s.parse_csv;
  { timestamp: s[0], url: s[1], ip: s[3] }
end
puts a
于 2013-08-14T13:38:47.330 回答