【问题标题】:Count the words for each country in a textfile via RDD通过 RDD 计算文本文件中每个国家/地区的单词
【发布时间】:2020-07-18 11:02:48
【问题描述】:

我正在尝试编写一个程序来通过 RDD 方法计算文本文件中每个国家/地区的单词。

样本数据:

India, It is having 1.5 Billion population
India, It is prospering in IT and manufacturing 
India, It has lot of natural mineral resources
US, It's global economic hub
US, It outsources IT work to India
US, It's global economic hub
US, It's global economic hub

例如,对于“India” - 所有单词有多少次等于“It”重复了多少次?

结果应该是这样的。

India, (It,3) ,(is,2)

...等等。美国也一样。

由于我使用的是 Databricks Notebook,因此不需要所有其他 Spark 会话和上下文,请查找以下方法。

val textRdd:RDD[String] = sc.textFile("/FileStore/tables/Data1")

val Rdd2 = textRdd.map(rec => rec.split(","))

val Rdd3 = Rdd2.map(rec => (rec(0),rec(1).split(" "))).collect()

def func(str1:String, arr1:Array[String]):(String,String) = {

  return (str1,arr1(_))

}

注意:Data1 有上面提到的数据。

有人可以帮忙吗?

【问题讨论】:

    标签: scala apache-spark rdd


    【解决方案1】:

    对于每一对(Country, word),可以进行count,然后按国家分组:

    // such format: ((India,is),2)
    val countryWordCountRDD = textRdd
      .map(rec => rec.split(","))
      .flatMap(r => r.last.trim.split(" ").map(w => (r.head, w)))
      .map((_, 1))
      .reduceByKey((a, b) => a + b)
    
    val result = countryWordCountRDD.map({ case ((country, word), counter) => (country, (word, counter)) })
        .groupByKey()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-13
      相关资源
      最近更新 更多