How to wrap Ruby strings in HTML tags
I'开发者_如何学Cm 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!
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
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
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>"
精彩评论