Запуск python mapreduce для нескольких файлов - PullRequest
1 голос
/ 03 апреля 2019

Я пытаюсь реализовать python mapreduce для нескольких файлов в каталоге, чтобы он принимал папку и строку в качестве аргумента и перечислял файлы с частотой этой строки в этих файлах. Вывод должен быть таким:
Вывод имени файла
-------- --------------
x.txt 8
y.txt 12

Я пытался реализовать это, но когда я запускаю его с помощью команды ниже: cat /home/habil/Downloads/hadoop_test/*.txt | python mapper.py "AA" | python reducer.py
Это дает мне «AA 479», которые являются частотой во всех 5 файлах

Это мой mapper.py

#!/usr/bin/env python
import sys
import textwrap
from os import listdir
from os.path import isfile, join




#Argument of the path
#folderPath = sys.argv[2]
#onlyfiles = [f for f in listdir(sys.argv[2]) if isfile(join(sys.argv[2], f))]
# Get the string sequence from the user
searchWord = sys.argv[1]
# Length of the word
searchWordLength = len(sys.argv[1])

# helper Function
def locations_of_substring(string, substring):
    """Return a list of locations of a substring."""
    substring_length = len(substring)
    def recurse(locations_found, start):
        location = string.find(substring, start)
        if location != -1:
            return recurse(locations_found + [location], location+substring_length)
        else:
            return locations_found

    return recurse([], 0)

#--- get all lines from stdin ---
for line in sys.stdin:
    #--- remove leading and trailing whitespace---
    line = line.strip()
    temp = locations_of_substring(line, searchWord)
    if len(temp) != 0:
        for count in temp:
            print '%s\t%s' % (line[count:count+searchWordLength], "1")

А ниже мой редуктор:

#!/usr/bin/env python
import sys

# maps words to their counts
word2count = {}

# 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:
        continue

    try:
        word2count[word] = word2count[word]+count
    except:
        word2count[word] = count

# write the tuples to stdout
# Note: they are unsorted
for word in word2count.keys():
    print '%s\t%s'% ( word, word2count[word])

Как получить желаемый результат, чтобы он запускался один раз для каждого файла в каталоге и выводил отдельные результаты. Любая помощь или подсказка приветствуется. Заранее спасибо.

...