@masonclayton/

Word frequency in a file

Ruby

No description

fork
loading
Files
  • main.rb
  • test.txt
main.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# a sample ruby program that determines the number of times each word in
# a file appears in that file (i.e., the frequency of that word).
#

the_file='./test.txt'

h = Hash.new
f = File.open(the_file, "r")

f.each_line { |line|
  words = line.force_encoding("utf-8").split
  words.each { |w|
    if h.has_key?(w)
      h[w] = h[w] + 1
    else
      h[w] = 1
    end
  }
}

# sort the hash by value, and then print it in this sorted order
h.sort{|a,b| a[1]<=>b[1]}.each { |elem|
  puts "\"#{elem[0]}\" has #{elem[1]} occurrences"
}
ruby 2.5.5p157 (2019-03-15 revision 67260) [x86_64-linux]