How to wrap Ruby strings in HTML tags

I am looking for help for two reasons. 1) I'm looking for a Ruby way to wrap strings in HTML. I have a program that I am writing that generates a hash of the frequency of words for a text file, and I want to take the results and put them in an HTML file, and not print to STDOUT. I think every line should be wrapped in an HTML paragraph tag using readlines () or something else, but I can't figure it out. Then, as soon as I wrapped the lines in HTML 2), I want to write to an empty HTML file.

Now my program looks like this:

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 and got:

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

I want to export to an HTML file that wraps strings, for example:

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

Thanks for any tips in advance!

+3
source share
3 answers

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
+3

- :

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
+2

, , . :

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>"
+1
source

Source: https://habr.com/ru/post/1784460/


All Articles