Ruby, Groovy, Scala ã§ã® Excelæºæ CSV ãã¡ã¤ã«ã®ãã¼ã¹å¦ç - opencsv使ç¨ãIterator.continually() ç
Excel ã®ä»æ§ã«æºæ ãã以ä¸ã®ãã㪠CSV ãã¡ã¤ã«ï¼æ¹è¡ã»ã«ã³ãã»ããã«ã¯ã©ã¼ãã¼ã·ã§ã³ãè¦ç´ å ã«å«ãï¼ããã¼ã¹ãã第1ã»3ã®è¦ç´ ãæ¨æºåºåã«åºåãããµã³ãã«ã RubyãGroovyãScala ã§ä½æãã¦ã¿ã¾ããã
CSVãã¡ã¤ã«ä¾ test.csv
1,ãã¹ã1,"æ¹è¡ å«ã¿" 2,test2,"ã«ã³ã,å«ã¿" 3,ã¦ãã¨3,"ããã«ã¯ã©ã¼ãã¼ã·ã§ã³""å«ã¿"
åºåçµæä¾
1 : æ¹è¡ å«ã¿ 2 : ã«ã³ã,å«ã¿ 3 : ããã«ã¯ã©ã¼ãã¼ã·ã§ã³"å«ã¿
ãµã³ãã«ã®ã½ã¼ã¹ã¯ http://github.com/fits/try_samples/tree/master/blog/20101129/
Ruby ã®å ´å
Ruby ã§ã¯æ¨æºæ·»ä»ããã¦ãã CSV ã©ã¤ãã©ãªã使ãã¾ãã
parse_csv.rb
require "csv" CSV.foreach(ARGV[0]) do |r| puts "#{r[0]} : #{r[2]}" end
以ä¸ã®ç°å¢ã§å®è¡ãã¦ã¿ã¾ããã
å®è¡ä¾
> ruby parse_csv.rb test.csv
> jruby parse_csv.rb test.csv
Groovy ã®å ´å
Groovy ãå¾è¿°ã® Scala ã«ã¯ä»åã®ã±ã¼ã¹ã®ãã㪠CSV ãã¡ã¤ã«ãç°¡åã«ãã¼ã¹ã§ããã©ã¤ãã©ãªãæ¨æºã§ç¨æããã¦ããªããããopencsv ã使ãäºã«ãã¾ãã
parse_csv.groovy
import java.io.FileReader import au.com.bytecode.opencsv.CSVReader def reader = new CSVReader(new FileReader(args[0])) while((r = reader.readNext()) != null) { println "${r[0]} : ${r[2]}" }
以ä¸ã®ç°å¢ã§å®è¡ãã¦ã¿ã¾ããã
- Groovy 1.7.5
- opencsv 2.2
å®è¡ä¾
> set CLASSPATH=opencsv-2.2.jar > groovy parse_csv.groovy test.csv
Scala ã®å ´å
Scala ã§ã opencsv ã使ãã¾ããã
ãã ããScala ã§ã¯ while((r = reader.readNext()) != null) ã®ããã«æ¸ããªãã®ã§ã代ããã« Iterator.continually(reader.readNext).takeWhile(_ != null) ã使ãã¾ãã
parse_csv.scala
import java.io.FileReader import au.com.bytecode.opencsv.CSVReader val reader = new CSVReader(new FileReader(args(0))) Iterator.continually(reader.readNext).takeWhile(_ != null).foreach {r => println(r(0) + " : " + r(2)) }
ã¾ãã以ä¸ã®ããã«Liståãã¦ãã¿ã¼ã³ãããã使ãæ¹æ³ããããã¨æãã¾ãã
parse_csv2.scala
import java.io.FileReader import au.com.bytecode.opencsv.CSVReader val reader = new CSVReader(new FileReader(args(0))) Iterator.continually(reader.readNext).takeWhile(_ != null).map(_.toList).foreach { case no :: title :: content :: _ => println(no + " : " + content) case _ => }
以ä¸ã®ç°å¢ã§å®è¡ãã¦ã¿ã¾ããã
- Scala 2.8.1
- opencsv 2.2
å®è¡ä¾
> scala -cp opencsv-2.2.jar parse_csv.scala test.csv
opencsv ã®ãã«ãæ¹æ³
http://sourceforge.net/projects/opencsv/ ãã opencsv-2.2-src-with-libs.tar.gz ãã¡ã¤ã«ããã¦ã³ãã¼ãããé©å½ãªãã£ã¬ã¯ããªã«å±éå¾ãAnt ã§ãã«ãããã°ãdeploy/opencsv-2.2.jar ãã¡ã¤ã«ãä½æããã¾ãã
ãã«ãä¾
> cd opencsv-2.2 > ant ã»ã»ã» BUILD SUCCESSFUL