火花Python地图

问题描述:

我有一些文字,我必须用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),如何使类似的第一个例子。感谢美国

如果你的问题是我如何在地图阶段发出多个值。答案是使用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(" ")返回一串字符串。