gpt4 book ai didi

scala - 需要从字符串中删除第一行,然后删除 scala 中的前两个单词

转载 作者:行者123 更新时间:2023-12-02 03:15:36 25 4
gpt4 key购买 nike

我需要导入一个文件并将其转换为字符串:

示例输入文件是:

#doc source topic proportion ...
0 src/main/resources/alpha1234 128 0.0651366607249073 26 0.05985658726301475 105 0.047919029870909846 173 0.04677118781397669

我只需要文件第二行的字符串的一部分。这是第二行的第三个单词。

预期输出字符串

128 0.0651366607249073 26 0.05985658726301475 105 0.047919029870909846 173 0.04677118781397669 

到目前为止我已经尝试过:

val inFile  = Source.fromResource("FileName").getLines.mkString(" ").drop(1)
val out = new BufferedWriter(new FileWriter("src/main/resources/newResult.txt"))
out.write(inFile)
out.close()

但是,它并没有删除第一行,而是仅删除第一个字母。

最佳答案

问题是您首先调用mkString,然后drop。函数mkStringIterator[String]转换为String,当您调用drop时,它适用于字符。让我们颠倒一下顺序:

val lines = Source
.fromResource("FileName")
.getLines
.toList // we convert Iterator to List to allow pattern matching
.drop(1) match { // we drop 1st line and then match the rest
// we match 1st line, split it by space, drop 2 first words and then assemble everything back together
case x :: xs => x.split(" ").drop(2).mkString(" ") :: xs
}

val inFile = lines.mkString(" ")

关于scala - 需要从字符串中删除第一行,然后删除 scala 中的前两个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56230955/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com