在包含HTML标签的文件上运行Hadoop MapReduce作业

1 投票
1 回答
2012 浏览
提问于 2025-04-15 16:40

我有一堆很大的HTML文件,我想用Hadoop的MapReduce来找出里面最常用的词。我用Python写了我的映射器和归约器,然后用Hadoop streaming来运行它们。

这是我的映射器:

#!/usr/bin/env python

import sys
import re
import string

def remove_html_tags(in_text):
'''
Remove any HTML tags that are found. 

'''
    global flag
    in_text=in_text.lstrip()
    in_text=in_text.rstrip()
    in_text=in_text+"\n"

    if flag==True: 
        in_text="<"+in_text
        flag=False
    if re.search('^<',in_text)!=None and re.search('(>\n+)$', in_text)==None: 
        in_text=in_text+">"
        flag=True
    p = re.compile(r'<[^<]*?>')
    in_text=p.sub('', in_text)
    return in_text

# input comes from STDIN (standard input)
global flag
flag=False
for line in sys.stdin:
    # remove leading and trailing whitespace, set to lowercase and remove HTMl tags
    line = line.strip().lower()
    line = remove_html_tags(line)
    # 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
       if word =='': continue
       for c in string.punctuation:
           word= word.replace(c,'')

       print '%s\t%s' % (word, 1)

这是我的归约器:

#!/usr/bin/env python

from operator import itemgetter
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)
        word2count[word] = word2count.get(word, 0) + count
    except ValueError:
        pass

sorted_word2count = sorted(word2count.iteritems(), 
key=lambda(k,v):(v,k),reverse=True)

# write the results to STDOUT (standard output)
for word, count in sorted_word2count:
    print '%s\t%s'% (word, count)

每当我用一个小的字符串,比如'hello world hello hello world ...'来测试时,我都能得到一个正确的排名列表。但是,当我尝试用一个小的HTML文件,并用cat命令把HTML内容传给我的映射器时,我却遇到了以下错误(input2包含一些HTML代码):

rohanbk@hadoop:~$ cat input2 | /home/rohanbk/mapper.py | sort | /home/rohanbk/reducer.py
Traceback (most recent call last):
  File "/home/rohanbk/reducer.py", line 15, in <module>
    word, count = line.split('\t', 1)
ValueError: need more than 1 value to unpack

有没有人能解释一下我为什么会遇到这个问题?另外,有什么好的方法来调试MapReduce的程序吗?

1 个回答

1

你可以只用以下代码就能重现这个错误:

echo "hello - world" | ./mapper.py  | sort | ./reducer.py

问题出在这里:

if word =='': continue
for c in string.punctuation:
           word= word.replace(c,'')

如果word是一个单独的标点符号,比如上面输入的情况(在分割之后),那么它会被转换成一个空字符串。所以,只需要把检查空字符串的部分放到替换之后就可以了。

撰写回答