首页 > 解决方案 > 通过 .filter 或 create 方法在 RDD 中添加元素?

问题描述

我想过滤一个 .txt 文件来创建 RDD 并生成统计信息。过滤器方法 (.filter) 允许我创建 RDD,但我受到限制,因为我的能力非常有限。

我想计算包含以下内容的单词数:

special characters >=3
uppercase >=1
lowercase >=1

过滤器使用示例:

   scala> val data = sc.textFile("file.txt") 
   scala> val specialChars = List('*', '@', '&', '=', '#', '?', '!', '%', '+', '-', '<', '>', ' ', ',', '_', '$', '"', '[', ']', ';', ''', '(', ')', '.', '/') 
   scala> val upper = List('A' to 'Z')
   scala> val lower = List('a' to 'z')           
   scala> val data_low = data.filter(_.length < 13).filter(line => !specialChars.exists(char => line.contains(char)))

这是我的另一种方法,但我不知道如何在 RDD 中实现结果(此处由 println 说明)。

scala> for (line <- data) {
     | var spe_sum = 0;
     | for (c <- specialChars) {
     | spe_sum = spe_sum + line.count(_ == c);
     | }
     | if (spe_sum >= 3 & nombre.exists(char => line.contains(char)) & maj.exists(char => line.contains(char)) & minus.exists(char => line.contains(char))) {
     | println(line);
     | }
     | }

是否可以在 .filter 中执行我的代码或编写 .filter 来执行相同的结果?

标签: scalaapache-spark

解决方案


欢迎来到堆栈溢出

filter方法循环遍历您提供的列表,并使用您提供的函数测试集合的每个元素。您的函数必须返回trueor false,并filter返回您的函数返回的列表元素true。因此,基本上,您不能使用过滤器来计算集合中的元素。

实现结果的方法如下

val rdd: RDD[String] = // load your RDD and tokenize each word
val specialChars = List('*', '@', '&', '=', '#', '?', '!', '%', '+', '-', '<', '>', ' ', ',', '_', '$', '"', '[', ']', ';', ''', '(', ')', '.', '/')
val upper = ('A' to 'Z')
val lower = ('a' to 'z')

// count the words satysfying all constraints
rdd.map(_.toList) // map each word to a list of chars
   .filter(x => specialChars.intersect(x).size > 2 && upper.intersect(x).nonEmpty && lower.intersect(x).nonEmpty)
   .count()

// count the words that satisfies at least a constraint
rdd.map(_.toList)
   .map(x => // map each word to a tuple of three elements, each element is to 1 if it satisfies the respective constraint
             (if (specialChars.intersect(x).size > 2) 1 else 0, // check the intersection with special characters
              if (upper.intersect(x).nonEmpty) 1 else 0,  // check the intersection with upper-case characters
              if (lower.intersect(x).nonEmpty) 1 else 0)) // check the intersection with lower-case characters
   .reduce((a, b) => (a._1 + b._1, a._2 + b._2, a._3 + b._3)) // sum up the results

结果元组的第一个元素是包含超过 3 个特殊字符的行数,第二个是至少包含一个大写字符的行数,第三个是至少包含一个小写字符的行数。


推荐阅读