Jing Archive Pages Categories Tags

ruby统计工程出现的单词

08 November 2014

words = {}
ARGV.each do |path|
File.open(path, "r") do |infile|
  while (line = infile.gets)
    line.scan(/[a-zA-Z]*[a-zA-Z]/).each do |word|
        if words.has_key?(word)
            words[word] = words[word] + 1
        else
            words[word] = 0
        end
    end
  end
end
end

wordsArray = words.sort_by {|key, value| value}
wordsArray.each do |str|
    print str
    print "\n"
end
Fork me on GitHub