2012-06-14 85 views
1

我寫了一個腳本解析一個.csv文件在groovy使用tokenize,最終沒有做到我所需要的,我試圖使用openCSV庫,但我不確定如何解析個別專欄。這裏是我到目前爲止的代碼:openCSV解析個別列

List<String[]> rows = new CSVReader(
    new InputStreamReader(getClass().classLoader.getResourceAsStream(inputFileString))) 
     .readAll() 

     rows.each { row -> 
      row.each { it -> 
       println it 
      } 
     } 

,這裏是我的輸入數據:

1,"unknown","positive","full message","I love it." 

所以我試圖找出是如何打印該行中選擇列。此外,在此先感謝,我試圖讓我的頭繞過groovy/java,我來自Ruby背景。

回答

2

不知道你的的意思「......如何選擇打印列說行」

但這腳本(例如)打印每一行的第4列:

@Grab('net.sf.opencsv:opencsv:2.3') 
import au.com.bytecode.opencsv.CSVReader 

// This sets example to a 2 line string 
// I'm using it instead of a file, as it makes 
// an easier example to follow 
def example = '''1,"unknown","positive","full message","I love it." 
       |2,"tim","negative","whoop!","It's ok"'''.stripMargin() 

List<String[]> rows = new CSVReader(new StringReader(example)).readAll() 

rows.each { 
    // print the 4th column 
    println it[ 3 ] 
} 

這打印:

full message 
whoop! 
+0

清理了很多,最後一件事情:如果我想打印多列?我需要創建一個單獨的varialbe,而不是it []默認值? –

+1

應該能夠做到:'println it [1,3]'例如打印第二個和第四個元素 –

+0

再次感謝,我最終宣佈了一個單獨的變量並進行插值。 :) –