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

使用Scala在Apache Spark中拆分字符串

发布时间:2020-12-16 09:50:51 所属栏目:安全 来源:网络整理
导读:我有一个数据集,其中包含格式的行(制表符分隔): TitletText 现在对于Text中的每个单词,我想创建一个(Word,Title)对. 例如: ABC Hello World 给我 (Hello,ABC)(World,ABC) 使用Scala,我写了以下内容: val file = sc.textFile("s3n://file.txt")val title
我有一个数据集,其中包含格式的行(制表符分隔):

Title<t>Text

现在对于Text中的每个单词,我想创建一个(Word,Title)对.
例如:

ABC      Hello World

给我

(Hello,ABC)
(World,ABC)

使用Scala,我写了以下内容:

val file = sc.textFile("s3n://file.txt")
val title = file.map(line => line.split("t")(0))
val wordtitle = file.map(line => (line.split("t")(1).split(" ").map(word => (word,line.split("t")(0)))))

但这给了我以下输出:

[Lscala.Tuple2;@2204b589
[Lscala.Tuple2;@632a46d1
[Lscala.Tuple2;@6c8f7633
[Lscala.Tuple2;@3e9945f3
[Lscala.Tuple2;@40bf74a0
[Lscala.Tuple2;@5981d595
[Lscala.Tuple2;@5aed571b
[Lscala.Tuple2;@13f1dc40
[Lscala.Tuple2;@6bb2f7fa
[Lscala.Tuple2;@32b67553
[Lscala.Tuple2;@68d0b627
[Lscala.Tuple2;@8493285

我该如何解决这个问题?

进一步阅读

我想要实现的是计算特定标题的文本中出现的单词数.

我写的后续代码是:

val wordcountperfile = file.map(line => (line.split("t")(1).split(" ").flatMap(word => word),line.split("t")(0))).map(word => (word,1)).reduceByKey(_ + _)

但它不起作用.请随时提供您的意见.谢谢!

解决方法

所以…在Spark中你使用称为RDD的分布式数据结构.它们提供类似于scala集合类型的功能.

val fileRdd = sc.textFile("s3n://file.txt")
// RDD[ String ]

val splitRdd = fileRdd.map( line => line.split("t") )
// RDD[ Array[ String ]

val yourRdd = splitRdd.flatMap( arr => {
  val title = arr( 0 )
  val text = arr( 1 )
  val words = text.split( " " )
  words.map( word => ( word,title ) )
} )
// RDD[ ( String,String ) ]

// Now,if you want to print this...
yourRdd.foreach( { case ( word,title ) => println( s"{ $word,$title }" ) } )

// if you want to count ( this count is for non-unique words),val countRdd = yourRdd
  .groupBy( { case ( word,title ) => title } )  // group by title
  .map( { case ( title,iter ) => ( title,iter.size ) } ) // count for every title

(编辑:李大同)

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

    推荐文章
      热点阅读