如何在 Scala 文件的行首添加一个元素
How to add an element at the beginning of a line in a file in Scala
我有一个文件,例如:
// file_1.txt
10 2 3
20 5 6
30 8 9
我需要在满足关于行中第一个值/数字的标准的每一行之前写一个带有 space 的字母,例如,如果我给出值 20,那么文件应该如下所示:
// file_1.txt
10 2 3
c 20 5 6
30 8 9
我如何在 Scala 中实现这一点?
这就是我目前正在尝试的方法:
import java.io._
import scala.io.Source
object Example_01_IO {
val s = Source.fromFile("example_01_txt")
val source = s.getLines()
val destination = new PrintWriter(new File("des_example_01.txt"))
val toComment = Array(-10, 20, -30)
def main(args: Array[String]): Unit = {
for (line <- source) {
//if(line_begins_with_any_value_from_toComments_then_write_a_"c"_infront_of_that_line){
println(line)
destination.write("c" + line)
destination.write("\n")
//}
}
s.close()
destination.close()
}
}
比方说,我可以写入另一个文件,但我需要写入同一个文件,并且只有当一行满足这样的条件时。
如有任何帮助,我将不胜感激。
从您所拥有的开始,您真正需要添加的是一种检查当前行是否以您 Array
.
中的数字开头的方法
一种方法是在每个 space 上拆分行,这样您就可以得到该行上所有数字的列表。然后只取该列表的第一个并将其转换为 Int
。然后您可以简单地检查 Int
是否存在于您的 Array
允许号码中。
import java.io._
import scala.io.Source
object Example_01_IO {
val s = Source.fromFile("example_01_txt")
val source = s.getLines()
val destination = new PrintWriter(new File("des_example_01.txt"))
val toComment = Array(-10, 20, -30)
def main(args: Array[String]): Unit = {
def startsWithOneOf(line: String, list: Array[Int]) =
list.contains(line.split(" ").head.toInt)
for (line <- source) {
val lineOut = if (startsWithOneOf(line, toComment)) s"c $line" else line
destination.write(lineOut)
destination.write("\n")
}
s.close()
destination.close()
}
}
我有一个文件,例如:
// file_1.txt
10 2 3
20 5 6
30 8 9
我需要在满足关于行中第一个值/数字的标准的每一行之前写一个带有 space 的字母,例如,如果我给出值 20,那么文件应该如下所示:
// file_1.txt
10 2 3
c 20 5 6
30 8 9
我如何在 Scala 中实现这一点?
这就是我目前正在尝试的方法:
import java.io._
import scala.io.Source
object Example_01_IO {
val s = Source.fromFile("example_01_txt")
val source = s.getLines()
val destination = new PrintWriter(new File("des_example_01.txt"))
val toComment = Array(-10, 20, -30)
def main(args: Array[String]): Unit = {
for (line <- source) {
//if(line_begins_with_any_value_from_toComments_then_write_a_"c"_infront_of_that_line){
println(line)
destination.write("c" + line)
destination.write("\n")
//}
}
s.close()
destination.close()
}
}
比方说,我可以写入另一个文件,但我需要写入同一个文件,并且只有当一行满足这样的条件时。
如有任何帮助,我将不胜感激。
从您所拥有的开始,您真正需要添加的是一种检查当前行是否以您 Array
.
一种方法是在每个 space 上拆分行,这样您就可以得到该行上所有数字的列表。然后只取该列表的第一个并将其转换为 Int
。然后您可以简单地检查 Int
是否存在于您的 Array
允许号码中。
import java.io._
import scala.io.Source
object Example_01_IO {
val s = Source.fromFile("example_01_txt")
val source = s.getLines()
val destination = new PrintWriter(new File("des_example_01.txt"))
val toComment = Array(-10, 20, -30)
def main(args: Array[String]): Unit = {
def startsWithOneOf(line: String, list: Array[Int]) =
list.contains(line.split(" ").head.toInt)
for (line <- source) {
val lineOut = if (startsWithOneOf(line, toComment)) s"c $line" else line
destination.write(lineOut)
destination.write("\n")
}
s.close()
destination.close()
}
}