【问题标题】:need to remove first line from a string and then first two word in scala需要从字符串中删除第一行,然后在 scala 中删除前两个单词
【发布时间】:2019-05-21 04:11:25
【问题描述】:

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

示例输入文件是:

#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()

但是,它不会删除第一行,而只是删除第一个字母。

【问题讨论】:

    标签: scala


    【解决方案1】:

    问题是您先调用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(" ")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-17
      • 1970-01-01
      • 1970-01-01
      • 2011-10-12
      • 2022-01-16
      相关资源
      最近更新 更多