首先安装分析工作
sudo pip install jieba -i http://pypi.doubanio.com/simple/
需求:求一本小说里面出现次数最多得人名
呆萌(demo)的代码将基于 Hadoop 的 Streaming 工作模式实现,Streaming 模式下 Hadoop 可以使用非 Java 编写的 MapReduce 程序。
数据:小说《天龙八部》
首先我们实现 Mapper 程序,Mapper 程序的作用就是:
- 从 stdin 标准输入中依次读取每一行。
- 对每一行使用 jieba 分词进行分词。
- 对分词得到的词汇列表进行 Map 操作:每个词都映射成(word,1)这样的二元组,并输出到标准输出 stdout 中。
mapper阶段:
#!/usr/bin/env python
# 引入 jieba 分词模块
import jieba
import sys
# 从 stdin 标准输入中依次读取每一行
for line in sys.stdin:
# 对每一行使用 jieba 分词进行分词
wlist = jieba.cut(line.strip())
# 对分词得到的词汇列表进行 Map 操作
for word in wlist:
try:
# 每个词都映射成(word,1)这样的二元组
# 输出到标准输出 stdout 中
print "%s\t1" % (word.encode("utf8"))
except:
pass
reduce阶段:
Reducer 程序比 Mapper 要复杂些,基本逻辑如下步骤:
- 从标准输入读取单词和词频。
- 对每个词出现的频次进行叠加,直到不再出现该词。
- 输出词和词频。
#!/usr/bin/env python
import sys
# 定义临时变量存储中间数据
current_word, current_count, word=None,1,None
# 依次从标准输入读取每一行
for line in sys.stdin:
try:
# 每一行都是一个(word,count)的二元组,从中提取信息词语和数量
line = line.rstrip()
word, count = line.split("\t", 1)
count = int(count)
except: continue
# 判断当前处理的词是从当前行提取的词
if current_word == word:
# 如果是,则增加当前处理的词出现的频次
current_count += count
else:
# 如果不是,则需要输出当前处理的词和词频到标准输出
if current_word:
print "%s\t%u" % (current_word, current_count)
current_count, current_word = count, word
# 读取完毕后需要处理当前词是读取词,但没有输出的情况
if current_word == word:
print "%s\t%u" % (current_word, current_count)
使用hadoop Streaming jar包执行 这mepper.py、reducer.py两个python脚本,执行命令:
hadoop jar hadoop-streaming-2.7.3.jar \-mapper / path / to /home/hadoop/hadoopWordCount/mapper.py \-reducer /home/hadoop/hadoopWordCount/reducer.py \-input /data/input/tlbbtestfile.txt \-output wordcountout1 \-jobconf mapred.map.tasks=4 \-jobconf mapred.reduce.tasks=2
这里遇到问题:
提示找不到文件!