2016-09-20 5 views
0
val sparkConf = new SparkConf().setAppName("ShortTwitterAnalysis").setMaster("local[2]") 
val sc = new SparkContext(sparkConf) 
val text = sc.textFile("/home/tobbyj/HW1_INF553/shortTwitter.txt") 
val twitter = text 
    .map(_.toLowerCase) 
    .map(_.replace("\t", "")) 
    .map(_.replace("\"", "")) 
    .map(_.replace("\n", "")) 
    .map(_.replace(".", "")) 
    .map(_.replaceAll("[\\p{C}]", "")) 
    .map(_.split("text:")(1).split(",source:")(0)) 
    .zipWithIndex.map(_.swap) 

上記のコードを使用して、以下のような結果が得られます。スカラのスパークで文章をマップ内の単語に分割する方法(case(key、value)=> ...)

(0,a rose by any other name would smell as sweet) 
(1,a rose is a rose is a rose) 
(4,rt @nba2k: the battle of two young teams tough season but one will emerge victorious who will it be? lakers or 76ers? https:\/\/tco\/nukkjq\u2026) 
(2,love is like a rose the joy of all the earth) 
(5,i was going to bake a cake and listen to the football flour refund?) 
(3,at christmas i no more desire a rose than wish a snow in may’s new-fangled mirth) 

しかし、私が欲しい結果は、私は以下のように見えるように起こっているのか分からないにも関わらず、ご理解のために、以下のような単語に分け、1から始まる「キー」と「値」です。私は疲れて

(1,(a, rose, by, any, other, name, would, smell, as, sweet)) 
(2,(a, rose, is, a, rose, is, a, rose)) 
... 

コードが

.map{case(key, value)=>(key+1, value.split(" "))} 

ですが、私に任意の提案

(1,[Ljava.lang.String;@1dff58b) 
(2,[Ljava.lang.String;@167179a3) 
(3,[Ljava.lang.String;@73e8c7d7) 
(4,[Ljava.lang.String;@7bffa418) 
(5,[Ljava.lang.String;@2d385beb) 
(6,[Ljava.lang.String;@4f1ab87e) 

以下のような結果を与えますか?このステップの後、私はそれらを(1、a)、(1、バラ)、(1、by)...(2、love)、(2、rose)...のようにマッピングします。

+2

これは、 'split'がタプル値として出力される' Array [String] 'を返すためです。 –

+0

それではどうしたらいいですか? – tobby

+0

何をしたいですか?値を出力したい場合、配列を 'foreach'する必要があります。 –

答えて

1

org.apache.spark.rdd.PairRDDFunctionshereと記載)をインポートすると、キーと値のペアでより簡単に作業できます。

この時点で、flatMapValuesメソッドを使用して必要な情報を取得できます。

(0,this) 
(0,is) 
(0,my) 
(0,first) 
(0,tweet) 
(1,and) 
(1,this) 
(1,is) 
(1,my) 
(1,second) 
(2,ok) 
(2,this) 
(2,is) 
(2,getting) 
(2,boring) 

あなたの場合:これは、このコードの数行の出力である

import org.apache.spark._ 
import org.apache.spark.rdd.PairRDDFunctions 

val conf = new SparkConf().setAppName("test").setMaster("local[*]") 
val sc = new SparkContext(conf) 

val tweets = sc.parallelize(Seq(
    "this is my first tweet", 
    "and this is my second", 
    "ok this is getting boring")) 

val results = 
    tweets. 
    zipWithIndex. 
    map(_.swap). 
    flatMapValues(_.split(" ")) 

results.collect.foreach(println) 

:ここでは、最小限の実施例である(ちょうどあなたがスパークコンソールである場合val tweetsを含む行からコピー) Spark StreamingでライブのTwitterフィードを分析する方法を示す小さな例を見ることに興味があります。hereがあります。

+0

これは私が欲しかったものです! – tobby

関連する問題