前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python使用Hadoop进行词频统计

Python使用Hadoop进行词频统计

作者头像
钱塘小甲子
发布2019-01-28 15:20:09
2.3K0
发布2019-01-28 15:20:09
举报

今天,我们利用python编写一个MapReduce程序,程序的目的还是百年不变的计算单词个数,也就是WordCunt。

所谓mapreduce其实就是先分散计算后综合处理计算结果。

首先我们来看一下map部分的代码。

代码语言:javascript
复制
#!/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)  

mapper其实只做了一个功能,就是读取每行文字,然后分割成一个一个的单词

reduce部分代码:

代码语言:javascript
复制
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)  

这里,其实是对上面的map步骤的输出做处理。

然后,我们把一本英语小说放到HDFS上,也就是bin/hdfs dfs下的命令。

接下来,调用如下命令:

bin/hadoop jar share/hadoop/tools/lib/hadoop-streaming-2.2.0.jar -files ./mapper.py,./reducer.py -mapper ./mapper.py -reducer ./reducer.py -input /book/test.txt -output book-out

也就是说,我们是用streaming来实现python编写和运行mapreduce的。这里-input 后是hdfs中我们放置文件的路径,也就是英语小说的路径,-output 则是输出结果的路径。

bin/hdfs dfs -cat /user/hadoops2/book-out/part-00000 | sort -nk 2 | tail

最后,我们可以用这个命令查看运行结果的尾部几条。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016年12月25日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
大数据
全栈大数据产品,面向海量数据场景,帮助您 “智理无数,心中有数”!
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档