Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何通过读取CSV文件在scala中创建映射[Int,Set[String]]?_Scala_Csv - Fatal编程技术网

如何通过读取CSV文件在scala中创建映射[Int,Set[String]]?

如何通过读取CSV文件在scala中创建映射[Int,Set[String]]?,scala,csv,Scala,Csv,我想通过读取CSV文件中的输入,在scala中创建Map[Int,Set[String]] 我的file.csv是 sunny,hot,high,FALSE,no sunny,hot,high,TRUE,no overcast,hot,high,FALSE,yes rainy,mild,high,FALSE,yes rainy,cool,normal,FALSE,yes rainy,cool,normal,TRUE,no overcast,cool,normal,TRUE,yes 我希望输出为

我想通过读取CSV文件中的输入,在scala中创建Map[Int,Set[String]]

我的file.csv是

sunny,hot,high,FALSE,no
sunny,hot,high,TRUE,no
overcast,hot,high,FALSE,yes
rainy,mild,high,FALSE,yes
rainy,cool,normal,FALSE,yes
rainy,cool,normal,TRUE,no
overcast,cool,normal,TRUE,yes
我希望输出为

var Attributes = Map[Int,Set[String]] = Map()

Attributes += (0 -> Set("sunny","overcast","rainy"))
Attributes += (1 -> Set("hot","mild","cool"))
Attributes += (2 -> Set("high","normal"))
Attributes += (3 -> Set("false","true"))
Attributes += (4 -> Set("yes","no"))
此0,1,2,3,4表示列编号,集合包含每列中的不同值

我想将每个(Int->Set(String))添加到我的属性“Attributes”中。也就是说,如果我们打印Attributes.size,它将显示5(在本例中)。

使用其中一个来读取CSV文件。您将有一个二维数组或字符串向量。然后建立你的地图

// row vectors
val rows = io.Source.fromFile("file.csv").getLines.map(_.split(",")).toVector
// column vectors
val cols = rows.transpose
// convert each vector to a set
val sets = cols.map(_.toSet)
// convert vector of sets to map
val attr = sets.zipWithIndex.map(_.swap).toMap
最后一行有点难看,因为没有直接的
.toMap
方法。你也可以写

val attr = Vector.tabulate(sets.size)(i => (i, sets(i))).toMap
或者,您可以一次性完成最后两个步骤:

val attr = cols.zipWithIndex.map { case (xs, i) => 
  (i, xs.toSet) 
} (collection.breakOut): Map[Int,Set[String]]

请看,了解如何将这些行读入内存。要避免性能问题,请考虑使用<代码>流< /代码>。code>zipWithIndex将为您提供每行的行号。迭代这些行并创建您的
地图
。希望这有帮助!如果我使用另一个数据集,它会显示一个错误,即线程“main”java.lang.IllegalArgumentException中的异常:transpose要求所有集合具有相同的大小