title: How do I count the number of instances of particular words in a paragraph?
body: <p>I'd like to count the number of times a set of words appear in each paragraph in a text file. I am able to count the number of times a set of words appears in an entire text.</p>
  
  <p>It has been suggested to me that my code is really buggy, so I'll just ask what I would like to do, and if you want, you can look at the code I have at the bottom.</p>
  
  <p>So, given that "frequency_count.txt" has the words "apple pear grape melon kiwi" in it, I want to know how often "apple" shows up in each paragraph of a separate file "test_essay.txt", how often pear shows up, etc., and then for these numbers to be printed out in a series of lines of numbers, each corresponding to a paragraph.</p>
  
  <p>For instance:</p>
  
  <pre><code>apple, pear, grape, melon, kiwi
  3,5,2,7,8
  2,3,1,6,7
  5,6,8,2,3
  </code></pre>
  
  <p>Where each line corresponds to one of the paragraphs. </p>
  
  <p>I am very, very new to Ruby, so thank you for your patience. </p>
  
  <pre><code>output_file = '/Users/yirenlu/Quora-Personal-Analytics/weka_input6.csv'
  o = File.open(output_file, "r+")
  
  common_words = '/Users/yirenlu/Quora-Personal-Analytics/frequency_count.txt'
  c = File.open(common_words, "r")
  
  c.each_line{|$line1|
      words1 = $line1.split
      words1.each{|w1|
          the_file = '/Users/yirenlu/Quora-Personal-Analytics/test_essay.txt'
          f = File.open(the_file, "r")
          rows = File.readlines("/Users/yirenlu/Quora-Personal-Analytics/test_essay.txt")
          text = rows.join
          paragraph = text.split(/\n\n/)
          paragraph.each{|p|
              h = Hash.new
              puts "this is each paragraph"
              p.each_line{|line|
                  puts "this is each line"
                  words = line.split
                  words.each{|w|
                      if w1 == w
                          if h.has_key?(w)
                              h[w1] = h[w1] + 1
                          else
                              h[w1] = 1
                          end
                          $x = h[w1]
                      end
                  }
              }
              o.print "#{$x},"
          }
      }
      o.print "\n"
      o.print "#{$line1}"
  }
  </code></pre>