scala - 通过 .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 来执行相同的结果?
解决方案
欢迎来到堆栈溢出
该filter
方法循环遍历您提供的列表,并使用您提供的函数测试集合的每个元素。您的函数必须返回true
or 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 个特殊字符的行数,第二个是至少包含一个大写字符的行数,第三个是至少包含一个小写字符的行数。
推荐阅读
- vb.net - 如何使用 SQL 到 VB.net 在 Chart1 中获取 X 和 Y
- bash - linux shell脚本源目标复制目录
- c - Compilation flag to handle long path/filename in I/O operations in Visual Studio
- java - 如何使用 Java 将 SVG 文件中的多个路径组合成单个路径
- git - 安装后删除fail2ban.git是否安全?
- java - Java中如何优化同步方法
- python - PyQt4 QtCore.QObject.connect(..., QtCore.SIGNAL(...), ...) 到 PyQt5
- node.js - 在生产服务器中重新加载 Angular 应用程序会产生 404
- php - 如何使用单个表以不同形式在codeigniter中查看数据库中的多个复选框值
- python - 实现代表“带有标题的列表”的类的pythonic方法是什么?