Jason Heppler
Jason Heppler

Reputation: 716

How to wrap Ruby strings in HTML tags

I'm looking for help on two things. 1) I'm looking for a way for Ruby to wrap strings in HTML. I have a program I'm writing that generates a Hash of word frequencies for a text file and I want to take the results and place it into an HTML file rather than print to STDOUT. I'm thinking each string needs to be wrapped in an HTML paragraph tag using readlines() or something, but I can't quite figure it out. Then, once I've wrapped the strings in HTML 2) I want to write to an empty HTML file.

Right now my program looks like:

filename = File.new(ARGV[0]).read().downcase().scan(/[\w']+/)
frequency = Hash.new(0)
words.each { |word| frequency[word] +=1 }
frequency.sort_by { |x,y| y }.reverse().each{ |w,f| puts "#{f}, #{w}" }

So if we ran a text file through this and received:

35, the
27, of
20, to
16, in
# . . .

I'd want to export to an HTML file that wraps the lines like:

<p>35, the</p>
<p>27, of</p>
<p>20, to</p>
<p>16, in</p>
# . . .

Thanks for any tips in advance!

Upvotes: 3

Views: 3192

Answers (3)

sawa
sawa

Reputation: 168071

You may want to look into the dom gem that I have developed. Your string can be generated like this:

require "dom"

frequency.sort_by(&:last).reverse.map{|w, f| "#{f}, #{w}".dom(:p)}.dom
# => "<p>35, the</p><p>27, of</p><p>20, to</p><p>16, in</p>"

Upvotes: 1

Jacob Relkin
Jacob Relkin

Reputation: 163228

This is a trivial problem.

#open file, write, and close

File.open('words.html', 'w') do |ostream|
  words = File.new(ARGV[0]).read.downcase.scan(/[\w']+/)
  frequency = Hash.new
  words.each { |word| frequency[word] +=1 }

  frequency.sort_by {|x, y| y }.reverse.each do |w,f| 
     ostream.write "<p>#{f}, #{w}</p>" 
  end
end

Upvotes: 3

Cody Caughlan
Cody Caughlan

Reputation: 32748

Something like this:

File.open("output.html", "w") do |output|

  words = File.new(ARGV[0]).read().downcase().scan(/[\w']+/)
  frequency = Hash.new(0)
  words.each { |word| frequency[word] +=1 }
  frequency.sort_by { |x,y| y }.reverse().each do |w,f| 
   output.write "<p>#{f}, #{w}</p>\n"
  end

end

Upvotes: 2

Related Questions