我正在读取一个 csv 文件以存储在不可变的数据结构中。每一行都是一个入口。每个入口都有一个车站。每个车站可以有多个入口。有没有一种方法可以一次通过而不是您在下面看到的两次通过?
object NYCSubwayEntrances {
def main(args: Array[String]) = {
import com.github.tototoshi.csv.CSVReader
//http://www.mta.info/developers/data/nyct/subway/StationEntrances.csv
val file = new java.io.File("StationEntrances.csv")
val reader = CSVReader.open(file)
reader.readNext //consume headers
val entranceMap = list2multimap(
reader.all map {
case fields: List[String] =>
// println(fields)
(
fields(2),
Entrance(
fields(14).toBoolean,
Option(fields(15)),
fields(16).toBoolean,
fields(17),
fields(18) match {case "YES" => true case _ => false},
fields(19) match {case "YES" => true case _ => false},
fields(20),
fields(21),
fields(22),
fields(23),
fields(24).toInt,
fields(25).toInt
)
)
}
)
reader.close
val reader2 = CSVReader.open(file)
reader2.readNext //consume headers
val stations = reader2.all map { case fields: List[String] =>
Station(
fields(2),
fields(0),
fields(1),
colate(scala.collection.immutable.ListSet[String](
fields(3),
fields(4),
fields(5),
fields(6),
fields(7),
fields(8),
fields(9),
fields(10),
fields(11),
fields(12),
fields(13)
)),
entranceMap(fields(2)).toList
)
}
reader2.close
import net.liftweb.json._
import net.liftweb.json.Serialization.write
implicit val formats = Serialization.formats(NoTypeHints)
println(pretty(render(parse(write(stations.toSet)))))
}
import scala.collection.mutable.{HashMap, Set, MultiMap}
def list2multimap[A, B](list: List[(A, B)]) =
list.foldLeft(new HashMap[A, Set[B]] with MultiMap[A, B]){(acc, pair) => acc.addBinding(pair._1, pair._2)}
def colate(set: scala.collection.immutable.ListSet[String]): List[String] =
((List[String]() ++ set) diff List("")).reverse
}
case class Station(name: String, division: String, line: String, routes: List[String], entrances: List[Entrance]) {}
case class Entrance(ada: Boolean, adaNotes: Option[String], freeCrossover: Boolean, entranceType: String, entry: Boolean, exitOnly: Boolean, entranceStaffing: String, northSouthStreet: String, eastWestStreet: String, corner: String, latitude: Integer, longitude: Integer) {}
可以在 https://github.com/AEtherSurfer/NYCSubwayEntrances找到具有所有正确依赖项的 sbt 项目
StationEntrances.csv 来自http://www.mta.info/developers/sbwy_entrance.html