コード中の文字の頻度分析
出題者です。 こちらで用意していた回答は awk を使ったものでした。一応解説すると、組み込み変数FSを空にし、1行単位の文字毎に連想配列に格納しています。
1 2 3 4 5 6 7 8 9 | # 1文字版
BEGIN { FS="" }
{ for (i=1; i<=NF; i++) ht[$i]++}
END { for (c in ht) print ht[c],c }
# 3文字版
BEGIN { FS="" }
{ for (i=1; i<=NF-2; i++) { ht[$i$(i+1)$(i+2)]++}}
END { for (c in ht) print ht[c],c }
|
Posted feedbacks - Erlang
ErlangのR13B3をCentOS5で展開したときの
erlang/lib/erlang/lib 以下の
*.erlの全ファイルをcatして1ファイルにまとめてから文字の頻度を調べてみました。39MBほどありました。
入力をバッファしているのは、単純に1文字ごとの入力を行うと実行がかなり遅かったためです。
ハイフンが多いのが目立ちますが、これは関数の定義などで多用されるためかもしれません。
'%'はコメントを示すために使われているので多いかもしれません。
"e", 6.5985% "-", 5.9863% "t", 4.5781%
",", 3.9575% "a", 3.6420% "s", 3.4442%
"r", 3.2970% "n", 3.2844%
"o", 2.8633%
"c", 2.6825%
"i", 2.6595%
"_", 2.5216%
"l", 1.9182%
"d", 1.9072%
"=", 1.5386%
"p", 1.5198%
")", 1.5170%
"(", 1.5167%
"%", 1.3770%
"T", 1.3100%
"m", 1.2499%
"u", 1.0674%
"S", 1.0670%
"y", 0.9540%
"g", 0.9246%
">", 0.8690%
"f", 0.8180%
"'", 0.7649%
"h", 0.6953%
"}", 0.6748%
"{", 0.6747%
"1", 0.6745%
"b", 0.6105%
"E", 0.6047%
"R", 0.5908%
"2", 0.5786%
"k", 0.5548%
"v", 0.5152%
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 27 28 29 30 31 32 33 34 35 36 | #!/usr/bin/env escript
main(Filename) ->
case file:read_file(Filename) of
{ok, S} -> buffered_loop(S,1);
{error, Why} -> {error, Why}
end.
%% buffering is required to manage huge heap_area for listdata
buffered_loop(S,N) ->
BUFSIZE = 40960,
if
(byte_size(S) < (N + BUFSIZE)) ->
loop(binary_to_list(S, N, byte_size(S))),
L = lists:sort(get()),
Total = sumup(L, 0),
io:format("Total characters : ~p~n",[Total]),
show_histgram(L,Total);
true ->
loop(binary_to_list(S, N, N + BUFSIZE)),
buffered_loop(S, N + BUFSIZE)
end.
loop([]) -> [];
loop([H|L]) -> incr(H), loop(L).
incr(Chr) ->
case Count = get(Chr) of
undefined -> put(Chr,1);
_ -> put(Chr,Count + 1)
end.
sumup([H|[]], Sum) -> {_,V} = H, Sum + V;
sumup([H|L], Sum) -> {_,V} = H, sumup(L, Sum + V).
show_histgram([H|[]], Total) -> {K,V} = H, io:format("~p,~8.4f\%~n",[[K], 100 * V / Total]);
show_histgram([H|L], Total) -> {K,V} = H, io:format("~p,~8.4f\%~n",[[K], 100 * V / Total]), show_histgram(L, Total).
|



crane
#6382()
Rating0/0=0.00
プログラムコード中の文字の頻度は言語によって相当にばらつきがあると思います。ある言語はピリオドが頻出するとか、別の言語はカッコの頻出頻度が高い、とか。そこで、
(その言語で書かれた「典型的な」プログラムコード、といえるようなものがあると良いのですが・・)
簡単すぎるという方は、複数文字にしてみたり単語の頻度にしてみてください。
参考;Wikipedia 頻度分析
http://ja.wikipedia.org/wiki/%E9%A0%BB%E5%BA%A6%E5%88%86%E6%9E%90
1 reply [ reply ]