You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scala文本处理需求:按规则替换指定行的第二个字段

Scala Text Processing Solution for Field Replacement

Got it, let's break down how to solve this text file processing task. The core requirement is to scan each line of the input file, and whenever we hit a line starting with 15, replace its second field with the second field from the most recent line that starts with 10.

Step-by-Step Solution Code

Here's a robust Scala implementation that handles edge cases (like 15 lines appearing before any 10 lines) and follows idiomatic Scala practices:

import scala.io.Source
import scala.util.Using

object TextProcessor {
  def main(args: Array[String]): Unit = {
    // Replace with your actual input file path
    val inputFilePath = "input.txt"
    // Optional: Uncomment and set path if you want to write results to a file
    // val outputFilePath = "output.txt"

    // Safely manage file resources with Using (auto-closes the file source)
    Using(Source.fromFile(inputFilePath)) { source =>
      // Track the most recent second field from lines starting with "10"
      var lastTenSecondField: Option[String] = None

      // Process each line in sequence
      val processedLines = source.getLines().map { line =>
        val fields = line.trim.split("\\s+") // Split on one or more whitespace characters
        if (fields.nonEmpty) {
          fields(0) match {
            case "10" =>
              // Update our tracked field if this line has at least 2 fields
              if (fields.length >= 2) {
                lastTenSecondField = Some(fields(1))
              }
              line // Keep the original line intact
            case "15" =>
              // Replace the second field only if we have a valid tracked value
              lastTenSecondField match {
                case Some(replacement) if fields.length >= 2 =>
                  // Reconstruct the line with the replaced second field
                  s"${fields(0)} $replacement ${fields.drop(2).mkString(" ")}"
                case _ =>
                  // Keep original line if no tracked value or line is malformed
                  line
              }
            case _ =>
              // All other lines stay exactly as they are
              line
          }
        } else {
          // Preserve empty lines
          line
        }
      }.toList

      // Print processed lines to the console
      processedLines.foreach(println)

      // Optional: Write processed lines to an output file
      // import java.io.PrintWriter
      // Using(new PrintWriter(outputFilePath)) { writer =>
      //   processedLines.foreach(writer.println)
      // }
    }.recover {
      case e: Exception => println(s"Error processing file: ${e.getMessage}")
    }
  }
}

Key Details Explained

  • Resource Safety: We use scala.util.Using to automatically close file handles, preventing resource leaks that can happen if you forget to close files manually.
  • Whitespace Handling: split("\\s+") works with lines that have multiple spaces between fields, which is a common quirk in such text formats.
  • Edge Case Handling:
    • If an 15 line shows up before any 10 lines, it stays unchanged instead of crashing the program.
    • Malformed lines (with fewer than 2 fields) are preserved rather than causing errors.
  • Flexibility: You can toggle between printing results to the console or writing to a file by uncommenting the optional file-writing section.

Example Input/Output

Input (input.txt):

10 location String
10 age String
10 Salary String
15 job String
10 Name String
15 Status String

Output:

10 location String
10 age String
10 Salary String
15 Salary String
10 Name String
15 Name String

内容的提问来源于stack exchange,提问作者user7770873

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:44:52