由于您将问题标记为 RDD,我假设您的字数数据是 RDD。
// Read text file
val sc = spark.sparkContext
val textFile: RDD[String] = sc.textFile("data.txt")
// So you have this as you said
val verbs = Array(Array("have", "have", "having", "had"), Array("give", "give", "gave", "given"), Array("take", "take", "took", "taken"))
val data= textFile
.flatMap(_.split(" ")) // Split each line to words/tokens its called tokenization (I used backspace as seperator if you have tabs as seperator use that)
.map(t => (t, 1)) // Generate count per token (i.e. (have, 1))
.reduceByKey(_ + _) // Count appearance of each token (i.e. (have, 5)
val t = data.map(d => (verbs.find(v => v.contains(d._1)).map(_.head).getOrElse(d._1), d._2)) // Generates RDD of (optional base verb, count for that verb) e.g (having, 5) => (have, 5), unknown verbs left as it is
.reduceByKey(_ + _) // Sum all values that having same base verb (have, 5), (have, 3) => (have, 8)
t.take(10).foreach(println)
其他选项(不收集动词)
// You dont have to collect this If you want
val verbs2 = sc.parallelize(Array(Array("have", "have", "having", "had"), Array("give", "give", "gave", "given"), Array("take", "take", "took", "taken"))) // This is the state before collect
.flatMap(v => v.map(v2 => (v2, v.head))) // This generates tuples of verb -> base verb (e.g had -> have)
.reduceByKey((k1, k2) => if (k1 == k2) k1 else k2) // Current verbs array generates (have -> have twice, this eliminates duplicate records)
val data2 = textFile
.flatMap(_.split(" ")) // Split each line to words/tokens its called tokenization (I used backspace as seperator if you have tabs as seperator use that)
.map(t => (t, 1)) // Generate count per token (i.e. (have, 1))
.reduceByKey(_ + _) // Count appearance of each token (i.e. (have, 5)
val t2 = verbs2.join(data2) // This will join two RDD by their keys (verbs -> (base verb, verb count))
.map(d => d._2) // This is what we need key is base verb, value is count of that verb
.reduceByKey(_ + _) // Sum all values that having same base verb (have, 5), (have, 3) => (have, 8)
t2.take(10).foreach(println)
当然,此答案假定您将始终拥有动词数组,并且第一个元素是基本形式。如果您想要在没有动词数组的情况下工作并将任何动词转换为实际上是 NLP(自然语言处理)任务的基本格式,并且您需要使用某种单词规范化技术,例如 this(如 EmiCareOfCell44 所示)。您还可以在 spark ML 库中找到此类过程的实现。