よく使う単語 TOP100を取り出してみる

30分プログラム、その594。よく使う単語 TOP100を取り出してみる。

http://gauc.no-ip.org/awk-users-jp/blis.cgi/DoukakuAWK_067にインスパアされました。元のやつではmanページについて調べているけど、gz圧縮を展開するのが面倒だったので手元にあったソースコードでやってみました。

せっかくのErlangなので、シングルコアマシンなのにmapreduceを使いました。mapreduceのコードは、Source Code | The Pragmatic Bookshelfからとってきました。

使い方

$ escript wc.erl *
[{["="],252},
 {["->"],147},
 {["it"],66},
 {["x"],38},
 {["is"],37},
 {["by"],37},
 {["n"],36},
 {["you"],35},
 {["/"],35},
 {["#!"],34},
 {["coding:utf-8"],34},
 {["Author:"],34},
 {["MIZUNO"],34},
 {["-*-"],34},
 {["Copyright(C)"],34},
 {["redistribute"],33},
 {["Timestamp:"],33},
 {["under"],33},
 {["my"],33},
 {["Hiroki"],33},
 {["modify"],33},
 {["software;"],33},
 {["program"],33},
 {["This"],33},
 {["can"],33},
 {["free"],33},
 {["mzpppp"],31},
 {["at"],31},
 {["dot"],31},

ソースコード

-module(wc).
-compile([export_all]).

scan_words(Io,Words) ->
    case io:fread(Io,"","~s") of
	{ok,Word} ->
	    scan_words(Io,[Word|Words]);
        {error,_} ->
	    io:get_chars(Io,"",1),
	    scan_words(Io,Words);
	eof ->
	    file:close(Io),
	    Words
    end.

map(Pid,Path) ->
    {ok,F} = file:open(Path,[read]),
    lists:foreach(fun (W)-> Pid ! {W,1} end, scan_words(F,[])).

%% F2(Key, [Val], AccIn) -> AccOut
reduce(Word,Count, Counts) ->
    [{Word,lists:sum(Count)} | Counts].

main(Files)->
    L = phofs:mapreduce(fun wc:map/2,fun wc:reduce/3,[],Files),
    io:format("~p~n",
	      [lists:sublist(lists:sort(fun({_,X},{_,Y})-> Y < X end,L),100)]).