0

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 ) ?

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

7 Comments

line contains List[Double] , List[Double] , Double , Double , Double. Yours code is throwing error.
So you want to filter out the Lists and the parens out of the string then?
Yes exactly. I need this in such a way let store result of converting string to tuple in result object. result._1 and result._2 should return List[Double], result._3,result._4,result._5 should return Double
@Asif , Please check the edit. It doesn't throw an error on my side btw. The idea is to just to get a list of numbers and then split and slice that list
Thanks a lot. It's working now. One more thing. Currently length of both lists is 5. What if length of lists increases? In each case length of both lists will remain same.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.