[英]How to read a file and store words to a list in scala?
我正在嘗試將txt文件中存在的所有單詞(標點和數字除外)存儲到列表中?
我對Scala還是很陌生,不知道該怎么做? 有人可以幫忙嗎?
編輯:
我現在是這樣做的:
for(line <- Source.fromFile("src/stop_words.txt").getLines())
{
//println(line)
lst = line
}
println(lst)
它在lst = line上給了我一條紅線,並說重新分配給val。 我不知道為什么:(
假設每行可以有多個單詞,一個更好的解決方案是
val words = """([A-Za-z])+""".r
val all = io.Source.fromFile("path/to/file.txt").getLines.flatMap(words.findAllIn).toList
您可以將scala.io.Source與regex和toList一起使用
io.Source.fromFile("path/to/file.txt").
getLines().
filter(_.matches("[A-Za-z]+")).
toList
更新 :
您文件中的內容是什么? 這個簡單的代碼按預期工作
val list = io.Source.fromBytes(
"""aaa
|bbb
|123
|.-ddg
|AZvb
""".stripMargin.toArray.map(_.toByte)).
getLines().
filter(_.matches("[A-Za-z]+")).
toList
println(list)
輸出:
List(aaa, bbb, AZvb)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.