您的位置:首页 > 运维架构 > Shell

用Python和Shell结合进行词频统计

2016-11-23 11:33 609 查看
1、示例测试文本
/Users/nisj/PycharmProjects/EsDataProc/word.txt
foo|-X-|foo|-X-|quux|-X-|iio|-X-|oo|-X-|pp|-X-|pp|-X-|oo
see|-X-|you|-X-|you|-X-|again|-X-|welcome|-X-|test
test|-X-|ddd|-X-|gggg|-X-|ggg
acc|-X-|aaa|-X-|dddd
bbb|-X-|ddd|-X-|ccc
ddd|-X-|ccc|-X-|aaa
wo|-X-|ni|-X-|ta
who|-X-|am|-X-|i
isds|wew|ww|-X-|kkxcx|-X-|xcxcxcxcxc

2、进行数据Map操作的Python
/Users/nisj/PycharmProjects/EsDataProc/wc_mapper.py
# -*- coding=utf-8 -*-
#!/usr/bin/env python
import sys

# 输入为标准输入stdin
for line in sys.stdin:
# 删除开头和结果的空格
line = line.strip()
# 以默认空格分隔行单词到words列表
words = line.split('|-X-|')
for word in words:
# 输出所有单词,格式为“单词,1”以便作为reduce的输入
print '%s\t%s' % (word, 1)

3、进行数据Reduce操作的Python
/Users/nisj/PycharmProjects/EsDataProc/wc_reducer.py
# -*- coding=utf-8 -*-
#!/usr/bin/env python
import sys

current_word = None
current_count = 0
word = None

#获取标准输入,即mapper.py的输出
for line in sys.stdin:
line = line.strip()
#解析mapper.py输出作为程序的输入,以tab作为分隔符
word,count = line.split('\t',1)
#转换count从字符型成整型
try:
count = int(count)
except ValueError:
#非字符时忽略此行
continue
#要求mapper.py的输出做排序(sort)操作,以便对连续的word做判断
if current_word == word:
current_count +=count
else:
if current_word:
#输出当前word统计结果到标准输出
print '%s\t%s' %(current_word,current_count)
current_count =count
current_word =word

#输出最后一个word统计
if current_word ==word:
print '%s\t%s' % (current_word,current_count)

4、测试的Shell
/Users/nisj/PycharmProjects/EsDataProc/wc_batch.sh
#!/bin/bash
echo "foo foo quux labs foo bar quux" |python ./wc_mapper.py
echo "foo foo quux labs foo bar quux" |python ./wc_mapper.py | sort -k1,1 |python ./wc_reducer.py
cat ./word.txt |python ./wc_mapper.py | sort -k1,1 |python ./wc_reducer.py
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: