python 的hadoop统计词频脚本实现

map阶段

# -*- coding: utf-8 -*-
import sys

for line in sys.stdin:
    line = line.strip()
    words = line.split()
    for word in words:
        print("%s\t%s" % (word, 1))

reduce阶段

# -*- coding: utf-8 -*-
import sys

current_word = None
current_count = 0
word = None

for line in sys.stdin:
    word, count = line.split('\t', 1)
    try:
        count = int(count)
    except ValueError:
        continue
    if current_word == word:
        current_count += count
    else:
        if current_word:
            print ('%s\t%s' % (current_word, current_count))
        current_word = word
        current_count = count

if current_word == word:
    print('%s\t%s' % (current_word, current_count))

 

posted @ 2020-08-28 16:30  威威后花园  阅读(260)  评论(0编辑  收藏  举报