通过RDD计算文本文件中每个国家的字数

问题描述 投票:-1回答:1

我正在尝试通过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

例如,对于“印度”-所有单词计数多少次就像“ 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个回答
0
投票

对于每对(国家/地区,单词),可以先进行计数,然后再按国家/地区分组:

// 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()
© www.soinside.com 2019 - 2024. All rights reserved.