2015-01-16 14 views
1

나는 단지 스파크 (pyspark)에서 단어를 세고 싶지만 문자 나 전체 문자열을 매핑 할 수 있습니다. 스파크 - 단어 카운트 테스트

내가 시도 : (전체 문자열)

v1='Hi hi hi bye bye bye word count' 
v1_temp=sc.parallelize([v1]) 
v1_map = v1_temp.flatMap(lambda x: x.split('\t')) 
v1_counts = v1_map.map(lambda x: (x, 1)) 
v1_counts.collect() 

또는 (단지 문자)

v1='Hi hi hi bye bye bye word count' 
v1_temp=sc.parallelize(v1) 
v1_map = v1_temp.flatMap(lambda x: x.split('\t')) 
v1_counts = v1_map.map(lambda x: (x, 1)) 
v1_counts.collect() 
+0

글쎄, 여기의 문제는 스파크가 아니기 때문에 탭으로 분할하려고합니다 : 'split ('\ t ')', 필요한 것은'split()'을 호출하는 것입니다. – nonsleepr

답변

2

당신이 sc.parallelize(sequence)을 수행 할 때 병렬로에 작동 할 것이다 RDD를 만들 수 있습니다. 첫 번째 경우에 시퀀스는 단일 요소 (전체 문장)를 포함하는 목록입니다. 두 번째 경우에 시퀀스는 문자열이며 파이썬에서는 문자 목록과 유사합니다. 병렬 단어를 계산하려면

당신은 할 수 :

from operator import add 

s = 'Hi hi hi bye bye bye word count' 
seq = s.split() # ['Hi', 'hi', 'hi', 'bye', 'bye', 'bye', 'word', 'count'] 
sc.parallelize(seq)\ 
    .map(lambda word: (word, 1))\ 
    .reduceByKey(add)\ 
    .collect() 

는 당신이 얻을 것이다 당신이 영숫자 단어를 계산하려면

[('count', 1), ('word', 1), ('bye', 3), ('hi', 2), ('Hi', 1)] 
1

,이 해결책이 될 수 있습니다

import time, re 
from pyspark import SparkContext, SparkConf 

def linesToWordsFunc(line): 
    wordsList = line.split() 
    wordsList = [re.sub(r'\W+', '', word) for word in wordsList] 
    filtered = filter(lambda word: re.match(r'\w+', word), wordsList) 
    return filtered 

def wordsToPairsFunc(word): 
    return (word, 1) 

def reduceToCount(a, b): 
    return (a + b) 

def main(): 
    conf = SparkConf().setAppName("Words count").setMaster("local") 
    sc = SparkContext(conf=conf) 
    rdd = sc.textFile("your_file.txt") 

    words = rdd.flatMap(linesToWordsFunc) 
    pairs = words.map(wordsToPairsFunc) 
    counts = pairs.reduceByKey(reduceToCount) 

    # Get the first top 100 words 
    output = counts.takeOrdered(100, lambda (k, v): -v) 

    for(word, count) in output: 
     print word + ': ' + str(count) 

    sc.stop() 

if __name__ == "__main__": 
    main() 
0

많은 온라인 버전의 wordcount가 있습니다.

#to count the words in a file hdfs:/// of file:/// or localfile "./samplefile.txt" 
rdd=sc.textFile(filename) 

#or you can initialize with your list 
v1='Hi hi hi bye bye bye word count' 
rdd=sc.parallelize([v1]) 


wordcounts=rdd.flatMap(lambda l: l.split(' ')) \ 
     .map(lambda w:(w,1)) \ 
     .reduceByKey(lambda a,b:a+b) \ 
     .map(lambda (a,b):(b,a)) \ 
     .sortByKey(ascending=False) 

output = wordcounts.collect() 

for (count,word) in output: 
    print("%s: %i" % (word,count))