加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – Spark中的每个文档字数

发布时间:2020-12-16 09:59:45 所属栏目:安全 来源:网络整理
导读:我正在学习Spark(在 Scala中)并且一直在试图弄清楚如何计算文件每一行上的所有单词. 我正在使用数据集,其中每行包含一个以制表符分隔的document_id和文档的全文 doc_1 full-textdoc_2 full-textetc.. 这是我在一个名为doc.txt的文件中的玩具示例 doc_1 new y
我正在学习Spark(在 Scala中)并且一直在试图弄清楚如何计算文件每一行上的所有单词.
我正在使用数据集,其中每行包含一个以制表符分隔的document_id和文档的全文

doc_1   <full-text>
doc_2   <full-text>
etc..

这是我在一个名为doc.txt的文件中的玩具示例

doc_1   new york city new york state
doc_2   rain rain go away

我认为我需要做的是转换为元组containsig

((doc_id,word),1)

然后调用reduceByKey()来加1.我写了以下内容:

val file = sc.textFile("docs.txt")
val tuples = file.map(_.split("t"))
            .map( x => (x(1).split("s+")
            .map(y => ((x(0),y),1 ))   ) )

这给了我认为我需要的中间代表:

tuples.collect

res0: Array[Array[((String,String),Int)]] = Array(Array(((doc_1,new),1),((doc_1,york),city),state),1)),Array(((doc_2,rain),((doc_2,go),away),1)))

但是如果在元组上调用reduceByKey会产生错误

tuples.reduceByKey(_ + )
<console>:21: error: value reduceByKey is not a member of org.apache.spark.rdd.RDD[Array[((String,Int)]]
              tuples.reduceByKey(_ + )

我似乎无法理解如何做到这一点.我想我需要对数组中的数组进行简化.我尝试了很多不同的东西但是像上面那样不断出错并且没有任何进展.
任何关于此的指导/建议都将非常感激.

注意:我知道https://spark.apache.org/examples.html上有一个单词计数示例,显示如何获取文件中所有单词的计数.但那是整个输入文件.我正在谈论获取每个文档的计数,其中每个文档在不同的行上.

解决方法

reduceByKey期望类型为RDD [(K,V)],而在第一个映射中执行拆分的瞬间,最终会得到一个RDD [Array […]],它不是所需的类型签名.您可以按照以下方式重新设计当前的解决方案……但它可能不会像在使用flatMap进行返工的代码之后阅读:

//Dummy data load
val file = sc.parallelize(List("doc_1tnew york city","doc_2train rain go away"))  

//Split the data on tabs to get an array of (key,line) tuples
val firstPass = file.map(_.split("t"))

//Split the line inside each tuple so you now have an array of (key,Array(...)) 
//Where the inner array is full of (word,1) tuples
val secondPass = firstPass.map(x=>(x(0),x(1).split("s+").map(y=>(y,1)))) 

//Now group the words and re-map so that the inner tuple is the wordcount
val finalPass = secondPass.map(x=>(x._1,x._2.groupBy(_._1).map(y=>(y._1,y._2.size))))

可能是更好的解决方案vvvv:

如果要保留当前结构,则需要从一开始就更改为使用Tuple2,然后使用flatMap:

//Load your data
val file = sc.parallelize(List("doc_1tnew york city","doc_2train rain go away"))
//Turn the data into a key-value RDD (I suggest caching the split,kept 1 line for SO)
val firstPass = file.map(x=>(x.split("t")(0),x.split("t")(1)))
//Change your key to be a Tuple2[String,String] and the value is the count
val tuples = firstPass.flatMap(x=>x._2.split("s+").map(y=>((x._1,1)))

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读