2014-12-04 61 views
0

我正在嘗試逐行讀取文件並將每行中的所有單詞存儲到列表中,然後對其執行一些計算。如何將文件的每一行中的單詞存儲到列表中scala

我做了以下內容:

for(line <- Source.fromFile("file1.txt").getLines()) 
{ 
    var words_in_line = line.split("\\s+") 
    println(words_in_line) 
} 

但是,這種打印類似:

[Ljava.lang.String;@3535a92b 
[Ljava.lang.String;@55f56157 

這是什麼?爲什麼它不在列表中的每行中打印單詞?

編輯:

我現在這樣做:

val w2 = """([A-Za-z])+""".r 
for(line <- Source.fromFile("/Users/Martha/Desktop/file1.txt").getLines.flatMap(w2.findAllIn)) 
{ 
    println("this is") 
    println(line) 

    var w1 = line.split("\\s+") 
    //var w2 = w1.deep.mkString(" ") 
    var w3 = line.split("\\s").toList 
    println(w3) 

} 

只得到的話,沒有數字或標點符號。但是,它只給出列表中單個單詞作爲輸出,而不是單詞列表中的單詞。這是爲什麼?

回答

0
var words_in_line = line.split("\\s+") 

//words_in_line is an Array 

你不能println(words_in_line)

打印Array嘗試

scala> var line="hey hello this is demo" 
line: String = hey hello this is demo 

scala> var words=line.split("\\s+") 
words: Array[String] = Array(hey, hello, this, is, demo) 

scala> words map println 
hey 
hello 
this 
is 
demo 
res8: Array[Unit] = Array((),(),(),(),()) 

你想List(hey, hello, this, is, demo)像當年

scala> var words=line.split("\\s+").toList 
words: List[String] = List(hey, hello, this, is, demo) 

scala> println(words) 
List(hey, hello, this, is, demo) 
+0

但是,這並不在單詞列表的形式打印出來!第一個將它打印爲單詞,第二個將它打印成一個字符串。我想將它打印爲List(abc,vdc,...) – 2014-12-04 05:16:21

+0

非常感謝!你能幫我多做一件事嗎?你能否在這個問題上閱讀我的編輯。我遇到了麻煩。 :( – 2014-12-04 05:35:07

0

當你做getLines和flatMap結果是單個別單詞列表。如果您需要在該行的單詞列表,你需要將這些2個呼叫分離:

for(line <- io.Source.fromFile("all.txt").getLines) { 
    val words = w2.findAllIn(line) 
    println("this is") 
    println(words.mkString(" ")) 
} 
-1
var w3 = line.split("\\s") 
w3.foreach(m -> println(m)) 
相關問題