WordCount in Python

This section includes source code and instruction to run the WordCount example written in Python.

Following is the source code for the mapper. Save this code to a file called WordCount_mapper.py:
#!/usr/bin/env python
import sys
for line in sys.stdin:
(key,value) = line.split('\t')
wordList = value.split(' ')
for word in wordList:
print(word.strip() + "\t1")
Following is the source code for the reducer. Save this code to a file called WordCount_reducer.py:
#!/usr/bin/env python
import sys
word = ""
sum = 0
for line in sys.stdin:
(key,value) = line.split('\t')
if word == key:
sum = sum + int(value)
else:
if word != "":
print(word + "\t" + str(sum))
word = key
sum = 1
if key != "": print(key + "\t" + str(sum))
To run this example for data stored in the words1 table (which includes the id and sentence columns) within the mapreduce_db database, run the following command:
mapreduce jar /nz/export/ae/products/netezza/mapreduce/current/mapreducestreaming.
jar
-db mapreduce_db
-input 'words1' 'id' 'sentence'
-output 'results' 'word' 'count'
-mapper 'WordCount_mapper.py'
-mapper_out_key_size 20
-mapper_out_value_size 20
-file <path to WordCount_mapper.py file>
-reducer 'WordCount_reducer.py'
-reducer_out_key_size 20
-reducer_out_value size 20
-file <path to WordCount_reducer.py file>

After execution, the command creates a results table containing two columns: word and count, both of VARCHAR(20) type.