简体   繁体   中英

Scala split string to tuple

I would like to split a string on whitespace that has 4 elements:

1 1 4.57 0.83

and I am trying to convert into List[(String,String,Point)] such that first two splits are first two elements in the list and the last two is Point. I am doing the following but it doesn't seem to work:

Source.fromFile(filename).getLines.map(string => { 
            val split = string.split(" ")
            (split(0), split(1), split(2))
        }).map{t => List(t._1, t._2, t._3)}.toIterator

How about this:

scala> case class Point(x: Double, y: Double)
defined class Point

scala> s43.split("\\s+") match { case Array(i, j, x, y) => (i.toInt, j.toInt, Point(x.toDouble, y.toDouble)) }
res00: (Int, Int, Point) = (1,1,Point(4.57,0.83))

You could use pattern matching to extract what you need from the array:

    case class Point(pts: Seq[Double])
    val lines = List("1 1 4.34 2.34")

    val coords = lines.collect(_.split("\\s+") match {
      case Array(s1, s2, points @ _*) => (s1, s2, Point(points.map(_.toDouble)))
    })

You are not converting the third and fourth tokens into a Point , nor are you converting the lines into a List . Also, you are not rendering each element as a Tuple3 , but as a List .

The following should be more in line with what you are looking for.

case class Point(x: Double, y: Double) // Simple point class
Source.fromFile(filename).getLines.map(line => { 
    val tokens = line.split("""\s+""") // Use a regex to avoid empty tokens
    (tokens(0), tokens(1), Point(tokens(2).toDouble, tokens(3).toDouble))
}).toList // Convert from an Iterator to List
case class Point(pts: Seq[Double])
val lines = "1 1 4.34 2.34"

val splitLines = lines.split("\\s+") match {
  case Array(s1, s2, points @ _*) => (s1, s2, Point(points.map(_.toDouble)))
}

And for the curious, the @ in pattern matching binds a variable to the pattern, so points @ _* is binding the variable points to the pattern *_ And *_ matches the rest of the array, so points ends up being a Seq[String].

There are ways to convert a Tuple to List or Seq, One way is

scala> (1,2,3).productIterator.toList
res12: List[Any] = List(1, 2, 3)

But as you can see that the return type is Any and NOT an INTEGER

For converting into different types you use Hlist of https://github.com/milessabin/shapeless

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM