multiprocessing で word count
検索を書いてみるついでに、並列処理でマップリデュースっぽいワードカウントをやってみた。
しかし大量のドキュメントを用意するのが面倒だったので、複数クエリでやってみる。文章と検索対象のどちらが共通か、っていう問題なので、やってることは同じ。
#!/usr/bin/env python # encoding:utf-8 from multiprocessing import Pool import urllib import re melos = "http://www.aozora.gr.jp/cards/000035/files/1567_14913.html" words = [u"メロス" , u"セリヌンティウス" , u"王様",u"妹" ] def get_source(url): return re.sub("<.*?>","",unicode( urllib.urlopen(url).read() ,"sjis")) text = get_source(melos) def count_word(word): return text.count(word) if __name__ == '__main__': txt = get_source(melos) result = Pool(len(words)).map( count_word, words ) print result
> python word_count.py
[78, 15, 4, 12]