Skip to content

Instantly share code, notes, and snippets.

@antonlindstrom
Created March 13, 2014 16:47
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save antonlindstrom/9532116 to your computer and use it in GitHub Desktop.
Save antonlindstrom/9532116 to your computer and use it in GitHub Desktop.
Spark Wordcount Job that lists the 20 most frequent words
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import sys
import re
from operator import add
from pyspark import SparkContext
def map_phase(x):
x = re.sub('--', ' ', x)
x = re.sub("'", '', x)
return re.sub('[?!@#$\'",.;:()]', '', x).lower().split(' ')
def pass_filter(x):
return (len(x) > 0 or x != " " or x != None)
if __name__ == "__main__":
if len(sys.argv) < 3:
print >> sys.stderr, "Usage: wordcount <master> <file>"
exit(-1)
sc = SparkContext(sys.argv[1], "PythonWordCountSorted")
lines = sc.textFile(sys.argv[2], 1)
counts = lines.flatMap(map_phase) \
.map(lambda x: (x, 1)) \
.reduceByKey(add) \
.filter(pass_filter)
output = counts.map(lambda (k,v): (v,k)).sortByKey(False).take(20)
for (count, word) in output:
print "%i: %s" % (count, word)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment