每一个可以努力的日子,都是一份厚礼。
单词统计Word Count – Map Reduce Program
2011-01-04 20:06
在学习Map Reduce方法时,Word Count(单词统计)程序是最基础的入门训练。不同的写法会有不同的执行效率,下面是用python写的一个示例。
Map:
#!/usr/bin/python
#
# WordCount mapper in Python
# Author: Zeng, Xi
# SID: 1010105140
# Email: zengxi@cuhk.edu.hk
import sys
import re
def main(argv):
line = sys.stdin.readline()
pattern = re.compile("[a-zA-Z][a-zA-Z0-9]*")
try:
while line:
for word in pattern.findall(line):
print word + "\t" + "1"
line = sys.stdin.readline()
except "end of file":
return None
if __name__ == "__main__":
main(sys.argv)
Reduce:
#!/usr/bin/python
#
# WordCount reducer in Python
# Author: Zeng, Xi
# SID: 1010105140
# Email: zengxi@cuhk.edu.hk
import sys
word_list = {}
## collect (key,val) pairs from sort phase
for line in sys.stdin:
try:
word, count = line.strip().split("\t", 2)
if word not in word_list:
word_list[word] = int(count)
else:
word_list[word] += int(count)
except ValueError, err:
sys.stderr.write("Value ERROR: %(err)s\n%(data)s\n" % {"err": str(err), "data": line})
## emit results
for word, count in word_list.items():
print " ".join([word, str(count)])
| 这篇文章由lovelucy于2011-01-04 20:06发表在编程。你可以订阅RSS 2.0 也可以发表评论或引用到你的网站。除特殊说明外文章均为本人原创,并遵从署名-非商业性使用-相同方式共享创作协议,转载或使用请注明作者和来源,尊重知识分享。 |
批评不自由
则赞美无意义

大约13年前
用split分割不行吗?要比这个简单多。代码少很多会
大约13年前
简单的做法会有很多。但我这里是写一个Map Reduce程序,运用分治的思想,目的是应用于大规模分布式系统中进行并行处理。
欢迎参考学习MapReduce分布式程序设计方法