ファイルのタグを数えるプログラム

#! /usr/bin/ruby
=begin
 * 使い方
> ruby counttag.rb *.html

htmlファイルを読んで、タグのリストを作る。
タグリストは「(使用回数)	(タグ)」で、回数の多いものほど上にくる
(例)
 5161	br
 2353	b
 1814	strong
 1349	p
  437	a href
=end

counter = Hash.new(0)
while gets
  $_.downcase!
  scan( %r!<([^/]\w*?)\b(.*?)>! ){|tag,attr|
    attrs = attr.scan(/name|href|class=".*?"/)
    tag << " " << attrs.sort!.join(";") if attrs != []
    counter[tag] += 1
  }
end

sorted = counter.sort_by{|tag,count| count}
sorted.reverse.each {|tag,count|
  printf("%5d\t<%s>\n", count, tag)
}

ハッシュを使ったタグカウンタを、カウンタ数でソートするというパターンは応用が効きそうです。