开发者

How to wrap Ruby strings in HTML tags

开发者 https://www.devze.com 2023-02-03 03:38 出处:网络
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'开发者_如何学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>"
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号