Asif
Asif

Reputation: 733

Convert string to Tuple in Scala

I have to read data from file and convert it to a Tuple. Sample data is

(List(-28.92706839930671, 70.0055196968918, 97.18634024152067, -0.8977639173269137, -20.95631222378548),List(-2.1642508141664965, -49.26719368168469, -77.6449011447281, -92.11164347698504, 39.31785782242422),8.387308243500957E10,0.95,0.1)

I am using following code to read data from file.

val dataSource = Source.fromFile("/path/3.txt")
val lines = dataSource.getLines()
for (line <- lines) {
  line 
}

How can I convert string line to Tuple of ( List[Double] , List[Double] , Double , Double , Double ) ?

Upvotes: 0

Views: 188

Answers (1)

jrook
jrook

Reputation: 3519

If the structure of your input is exactly like the sample in the question with no possibility of invalid input, one solution is to use the following in the for loop:

val ls = line.replaceAll("\\(", "")
  .replaceAll("\\)","")
  .replaceAll("List", "")
  .split(",")
(ls.slice(0,5).map(_.toDouble).toList, ls.slice(5,10).map(_.toDouble).toList,
  ls(10).toDouble, ls(11).toDouble, ls(12).toDouble)

Result:

(List[Double], List[Double], Double, Double, Double) = (List(-28.92706839930671, 70.0055196968918, 97.18634024152067, -0.8977639173269137, -20.95631222378548),List(-2.1642508141664965, -49.26719368168469, -77.6449011447281, -92.11164347698504, 39.31785782242422),8.387308243500957E10,0.95,0.1)

Upvotes: 1

Related Questions