here's a verbose ruby version:
def topx(str,x)
c = Hash.new(0)
str.split(/\s+/).each { |s| c[s] += 1 }
c.sort_by {|k,v| -v}.take(x)
end