Created
October 15, 2014 05:11
-
-
Save sai43/3f4e8314a63b5548bb0f to your computer and use it in GitHub Desktop.
analyze a text file, counting the occurrence of each word
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# using fibers count words number of occurences in a file | |
words = Fiber.new do | |
File.foreach("samp.txt") do |line| | |
line.scan(/\w+/) do |word| | |
Fiber.yield word.downcase | |
end | |
end | |
nil | |
end | |
counts = Hash.new(0) | |
while word = words.resume | |
counts[word] += 1 | |
end | |
counts.keys.sort.each {|k| puts "#{k}:#{counts[k]} "} | |
#without using fibers count words occurences in a file | |
=begin | |
counts = Hash.new(0) | |
File.foreach("samp.txt") do |line| | |
line.scan(/\w+/) do |word| | |
word = word.downcase | |
counts[word] += 1 | |
end | |
end | |
counts.keys.sort.each {|k| puts"#{k}:#{counts[k]} "} | |
=end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment