Уменьшение количества слов в 2 классах - PullRequest
0 голосов
/ 23 января 2019

Первоначально я написал:

previous_word = ""
word_ct = 0

for line in sys.stdin:
    word, count = line.split()
    if word == previous_word:
        word_ct += int(count)
    else:
        if previous_word != "":
            print(previous_word, word_ct)
        previous_word = word
        word_ct = int(count)

# Print the final word and count
print(previous_word, word_ct)

, который функционирует как счетчик слов.Теперь у меня есть классы спама / ветчины, и я хотел бы суммировать частичные подсчеты в общее число следующим образом:

#!/usr/bin/env python
"""
Reducer takes words with their class and partial counts and computes totals.
INPUT:
    word \t class \t partialCount 
OUTPUT:
    word \t class \t totalCount  
"""
import re
import sys

# initialize trackers
current_word = None
spam_count, ham_count = 0,0

# read from standard input
for line in sys.stdin:
    # parse input
    word, is_spam, count = line.split('\t')

    if current_word == word:
        #print(word, is_spam)
        if is_spam == 1:
            spam_count += int(count)
        else:    
            ham_count += int(count)
    else:
        if current_word:
            if is_spam == 1:
                print("%s\t%s\t%s" % (current_word, is_spam, spam_count))
                spam_count = int(count)
            else:
                print("%s\t%s\t%s" % (current_word, is_spam, ham_count))
                ham_count = int(count)
        current_word = word

if current_word == word:
    if int(is_spam) == 1:
        print("%s\t%s\t%s" % (word, is_spam, spam_count))
    else:
        print("%s\t%s\t%s" % (word, is_spam, ham_count))

При этом мой код в основном работает, но не обрабатывает первый элемент данных правильно.Используя:

!echo -e "one   1   1\none  0   1\none  0   1\ntwo  0   1" | reducer.py

Я получаю только:

one 0   2
two 0   1

Я обнаружил, что первая запись пропускается, потому что, если current_word: изменяет переменную is_spam, это кажется?эта итерация сбивает меня с толку ...

Источник: http://www.michael -noll.com / tutorials / writing-an-hadoop-mapreduce-program-in-python /

...