【问题标题】:How to create map for each line based on the column using scala?如何使用scala根据列为每一行创建地图?
【发布时间】:2014-11-15 15:56:32
【问题描述】:

我需要使用scala根据列为每一行创建映射,例如,

sunny,hot,high,FALSE,no
overcast,hot,high,FALSE,yes
rainy,mild,high,FALSE,yes

我想输出为,

RDD[List(
  Map(
    '0 -> 'sunny,
    '1 -> 'hot,
    '2 -> 'high,
    '3 -> 'false,
    '4 -> 'no
  ),
  Map(
    '0 -> 'overcast,
    '1 -> 'hot,
    '2 -> 'high,
    '3 -> 'false,
    '4 -> 'yes
  ),
  Map(
    '0 -> 'rainy,
    '1 -> 'mild,
    '2 -> 'high,
    '3 -> 'false,
    '4 -> 'yes
  )
)]

这里我们考虑每一列,列号是键,列值是键值对中的值。

【问题讨论】:

    标签: scala


    【解决方案1】:

    纯斯卡拉

    val s = """sunny,hot,high,FALSE,no
              |overcast,hot,high,FALSE,yes
              |rainy,mild,high,FALSE,yes""".stripMargin
    
    
    s.split("\n").map { line =>
      line.split(",").zipWithIndex.map{ case (word, idx) => idx -> word}.toMap
    }.toList
    

    yields:
    List(Map(0 -> sunny, 1 -> hot, 2 -> high, 3 -> FALSE, 4 -> no), 
         Map(0 -> overcast, 1 -> hot, 2 -> high, 3 -> FALSE, 4 -> yes), 
         Map(0 -> rainy, 1 -> mild, 2 -> high, 3 -> FALSE, 4 -> yes))
    

    • split 在分隔符上分割文本
    • zipWithIndex 将 Seq 映射到 (value, index) 的元组

      'Seq('a', 'b').zipWithIndex' 产生 'Seq[(Char, Int)] = List((a,0), (b,1))'


    我们可以将功能改进为:

    s.split("\n").map { line =>
      line.split(",").zipWithIndex.map(_.swap).toMap
    }.toList
    
    • 因为 'zipWithIndex' 的结果是元组,具有 swap 函数,所以我们不需要自己交换元素

    对于火花

    sc.textFile(<file-with-data>).map { line =>
      line.split(",").zipWithIndex.map(_.swap).toMap
    }
    

    感谢@Paul

    【讨论】:

    • 如果你用 sc.textFile(&lt;file-with-data&gt;) 替换 s.split("\n") 并删除 .toList,这应该可以在 Spark 上正常工作
    • 感谢@Paul - 我添加了你的改进(认为我需要学习 spark)
    • 我不太了解 Spark,但我学到了一点,只是为了回答关于它的另一个问题。有很多相当基本的问题被问到
    • @Paul,这是 RDD[...],我想通过读取文本文件来列出 [Map[Int,String]]
    • 这个答案的第一部分是纯 Scala。读取文本文件只是 Source.fromPath("myfile.txt").getLines()。如果您需要更多信息,请参阅alvinalexander.com/scala/…
    猜你喜欢
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 2019-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-20
    • 1970-01-01
    相关资源
    最近更新 更多