如何从文件中读取字符串,列表[int]

时间:2016-12-16 15:59:37

标签: scala list dictionary io

我有一个文本文件,其中包含以下几行:

SK1, 2, 3, 4, 5
SK2, 1, 3, 5, 1

我想读它并将它存储在Map [String,List [Int]]中,但是我写的代码就是Map [String,List [Any]],我不知道怎么做要解决这个问题。你能救我吗?

  def readFile(filename: String): Map[String, List[Any]] = {

var mapBuffer: Map[String, List[Any]] = Map()
try {
  for (line <- Source.fromFile(filename).getLines()) {
    val splitline = line.split(",").map(_.trim).toList

    mapBuffer = mapBuffer ++ Map(splitline.head -> splitline.tail)

  }
} catch {
  case ex: Exception => println("There was an exception, please try again.")
}
mapBuffer
}

我也试过

def readFile(filename: String): Map[String, List[Int]] = {

var mapBuffer: Map[String, List[Int]] = Map()
try {
  for (line <- Source.fromFile(filename).getLines()) {
    val splitline = line.split(",").map(_.trim).toList.map(_.toInt)

    mapBuffer = mapBuffer ++ Map(splitline.head -> splitline.tail)

  }
} catch {
  case ex: Exception => println("There was an exception, please try again.")
}
mapBuffer
}

但是这给了我Map [A​​ny,List [Int]]。任何帮助将不胜感激,谢谢。

1 个答案:

答案 0 :(得分:0)

def readFile(filename: String): Map[String, List[Int]] = {
  // map over lines in file
  Source.fromFile(filename).getLines.map{ line =>
    // split the line into head and tail
    val ::(head, tail) = line.split(",").map(_.trim).toList
    // convert the tail to Int type
    head -> tail.map(_.toInt)
  }
  .toMap // convert to Map
}