每一個可以努力的日子,都是一份厚禮。
單詞統計Word Count – Map Reduce Program
在學習Map Reduce方法時,Word Count(單詞統計)程序是最基礎的入門訓練。不同的寫法會有不同的執行效率,下面是用python寫的一個示例。
Map:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | #!/usr/bin/python # # WordCount mapper in Python # Author: Zeng, Xi # SID: 1010105140 # Email: [email protected] 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | #!/usr/bin/python # # WordCount reducer in Python # Author: Zeng, Xi # SID: 1010105140 # Email: [email protected] 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 也可以發表評論或引用到你的網站。除特殊說明外文章均為本人原創,並遵從署名-非商業性使用-相同方式共享創作協議,轉載或使用請註明作者和來源,尊重知識分享。 |
批評不自由
則讚美無意義
Google Chrome 20.0.1132.47 Linux 大約12年前
用split分割不行嗎?要比這個簡單多。代碼少很多會
Google Chrome 20.0.1132.57 Windows 7 大約12年前
簡單的做法會有很多。但我這裡是寫一個Map Reduce程序,運用分治的思想,目的是應用於大規模分布式系統中進行並行處理。
歡迎參考學習MapReduce分布式程序設計方法