hadoop maper reducer python
时间: 2024-01-25 11:05:10 浏览: 100
hadoop中map/reduce
Hadoop MapReduce是一个分布式计算框架,可以用于处理大规模数据集。Mapper和Reducer是MapReduce的两个主要组件。Python是一种流行的编程语言,也可以用于编写Hadoop MapReduce作业。
在Python中编写MapReduce作业,您可以使用Hadoop Streaming API。该API允许您使用任何可执行文件作为Mapper和Reducer。以下是一个使用Python编写Mapper和Reducer的示例:
Mapper:
```python
#!/usr/bin/env python
import sys
# input comes from STDIN (standard input)
for line in sys.stdin:
# remove leading and trailing whitespace
line = line.strip()
# split the line into words
words = line.split()
# increase counters
for word in words:
# write the results to STDOUT (standard output);
# what we output here will be the input for the
# Reduce step, i.e. the input for reducer.py
#
# tab-delimited; the trivial word count is 1
print '%s\t%s' % (word, 1)
```
Reducer:
```python
#!/usr/bin/env python
from operator import itemgetter
import sys
current_word = None
current_count = 0
word = None
# input comes from STDIN
for line in sys.stdin:
# remove leading and trailing whitespace
line = line.strip()
# parse the input we got from mapper.py
word, count = line.split('\t', 1)
# convert count (currently a string) to int
try:
count = int(count)
except ValueError:
# count was not a number, so silently
# ignore/discard this line
continue
# this IF-switch only works because Hadoop sorts map output
# by key (here: word) before it is passed to the reducer
if current_word == word:
current_count += count
else:
if current_word:
# write result to STDOUT
print '%s\t%s' % (current_word, current_count)
current_count = count
current_word = word
# do not forget to output the last word if needed!
if current_word == word:
print '%s\t%s' % (current_word, current_count)
```
这些脚本可以使用Hadoop Streaming API提交为MapReduce作业,如下所示:
```bash
$HADOOP_HOME/bin/hadoop jar $HADOOP_HOME/share/hadoop/tools/lib/hadoop-streaming-2.7.3.jar \
-input input_file \
-output output_directory \
-mapper mapper.py \
-reducer reducer.py \
-file mapper.py \
-file reducer.py
```
其中,input_file是输入文件的路径,output_directory是输出目录的路径,mapper.py和reducer.py是上述Python脚本的文件名。
阅读全文