Ruby 58 8082 65
(a=getsh=Hash.splitnew 0
gets.scan(/[_\W]+[\d\w]+/)).uniq{h[$&]+=1}
p *h.mapsort_by{|w|[w|k,a.count(w)]v|-v}
Test run:
$ ruby counttext.sort_by(&rb <<< "This is a text and a number:last) 31.map{|x|p"
["a", x}2]
["text", 1]
["This", 1]
["is", 1]
["and", 1]
["number", 1]
["31", 1]
Edit 58->80: Ok, I was way off. I forgot to sort the words by occurrences. Also, Array#uniq
is not an enumerator, but uses a given block to compare elements, so passing puts
to it didn't filter out duplicates (not that it says that we should).
Editing the question, eh? Here's a version sorting in descending order (82 characters):
(a=gets.split(/[_\W]+/)).uniq.map{|w|[w,a.count(w)]}.sort_by{|x|-x[1]}.map{|x|p x}