2014-11-04 27 views
0

我在解析Scala中的TSV文件時遇到了一些問題。以下是對代碼執行操作的代碼。Scala import TSV

var lines = file.map(_.split('\n')) 
var nodes = lines.foreach(_.split('\t').map(_(1),_(2)).groupBy(_(1)).reduceByKey(_ + _)) 

輸入

1 a 24 
2 a 3 
3 b 6 

期望的操作

a 27 
b 6 

我上進行分割( '\ T')援引它不是陣列中的一員得到一個錯誤[字符串]這很奇怪,因爲foreach中的_應該引用每次一個元素。感謝您的幫助

+0

什麼是'文件'的類型? – 2014-11-04 22:22:06

+0

file應該是一個字符串,因爲它是通過'''file = sc.texFile(path)''' – 2014-11-04 22:23:17

回答

2

首先,foreach的分配是Unit,所以這不是你想要的。使用不可變的vals。目前還不清楚什麼格式的文件,所以你必須在那裏得到一個字符串。

val file = "1\ta\t24\n2\ta\t3\n3\tb\t6" 

val lines = file.split("\n") 
val nodes = lines.map(_.split("\t")).map(a => (a(1),a(2))).groupBy(_._1).map(a => (a._1,a._2.map(b => b._2.toInt).sum)) 
//Map(b -> 6, a -> 27) 

這是一個大熱的一塌糊塗,所以我會試着打破它:

val lines = file.split("\n")   //split string into array of lines 
val nodes = lines.map(_.split("\t")) //split each line into array of strings 
    .map(a => (a(1),a(2)))    //get just the second two items from the array as a tuple 
    .groupBy(_._1)      //group by the first item in the tuple 
    .map(a => (a._1,a._2.map(b => b._2.toInt).sum)) //take each tuple and map the second value (an array of strings) into an array of ints and get the sum 

如果你不喜歡的地圖的最終輸出可以方便地與toList或地圖更改映射到任何你想要的。

+0

讀取的。「原始錯誤仍然存​​在:'''value split不是Array [String]的成員'''on line.map(_。split('\ t')''' – 2014-11-04 23:09:42

+0

我用'''flatMap''解決了這個問題 – 2014-11-05 06:45:15

+0

很高興你解決了這個問題。文件類型不是你想象的那樣當我在我的響應中使用文件作爲字符串時,行的值是List [String],你得到了什麼? – Gangstead 2014-11-05 16:14:20