[英]Scala read file and split and modify each line
I'm new to Scala. 我是Scala的新手。 I want to read lines from a text file and split and make changes to each lines and output them. 我想从文本文件中读取行并拆分并对每行进行更改并输出它们。
Here is what I got: 这是我得到的:
val pre:String = " <value enum=\""
val mid:String = "\" description=\""
val sur:String = "\"/>"
for(line<-Source.fromFile("files/ChargeNames").getLines){
var array = line.split("\"")
println(pre+array(1)+mid+array(3)+sur);
}
It works but in a Object-Oriented programming way rather than a Functional programming way. 它的工作原理是面向对象的编程方式,而不是函数式编程方式。
I want to get familiar with Scala so anyone who could change my codes in Functional programming way? 我想熟悉Scala,以便任何能够以函数式编程方式更改代码的人?
Thx. 谢谢。
One traversal and no additional memory 一次遍历,没有额外的记忆
Source
.fromFile("files/ChargeNames")
.getLines
.map { line =>
//do stuff with line like
line.replace('a', 'b')
}
.foreach(println)
Or code which is a little bit faster, according to @ziggystar 或@ziggystar表示 ,代码更快一点
Source
.fromFile("files/ChargeNames")
.getLines
.foreach { line =>
//do stuff with line like
println(line.replace('a', 'b'))
}
val ans = for (line <- Source.fromFile.getLines) yield (line.replace('a', 'b')
ans foreach println
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.