2015-04-02 61 views
0

我有一些文字,我必須用hadoop計算一些單詞(如約翰和結婚)的計數。火花Python地圖

在Java腳本,我可以這樣寫:

require('timothy').map(function(line){ 
     emit("count", 1); 
     if(new RegExp("john", "i").test(line))  emit("John", 1); 
     if(new RegExp("marry", "i").test(line)) emit("Marry", 1); 
    }).reduce(function(key, values){ 
     var result = 0; 
     values.forEach(function(value){ 
      result += +value; 
     }); 

     emit(key, result); 
}).run(); 

我使用地圖功能適用於所有線路和寫入數據的每場比賽。現在我想用Spark做到這一點,但我必須用python寫。我有一些代碼:

import sys 
import re 

from operator import add 
from pyspark import SparkContext 

if __name__ == "__main__": 
    if len(sys.argv) != 2: 
     print >> sys.stderr, "Usage: wordcount <file>" 
     exit(-1) 
    sc = SparkContext(appName="PythonWordCount") 
    lines = sc.textFile(sys.argv[1], 1) 

    def map(line): 
     #here must contains map function; 


    counts = lines.map(map).reduceByKey(add) 
    output = counts.collect() 
    for (word, count) in output: 
     print "%s: %i" % (word, count) 

    sc.stop() 

我的問題是,我只能記錄一個匹配返回(鍵,VAL),如何使類似的第一個例子。感謝美國

回答

0

如果你的問題是我如何在地圖階段發出多個值。答案是使用flatMap運算符,該運算符返回一個值序列而不是單個值。該序列將被flatMap轉換分割。例如:

file = spark.textFile("file://...") 
counts = file.flatMap(lambda line: line.split(" ")) \ 
     .map(lambda word: (word, 1)) \ 
     .reduceByKey(lambda a, b: a + b) 

line.split(" ")返回一串字符串。