简体   繁体   English

如何在HTML标记中包装Ruby字符串

[英]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. 1)我正在寻找一种方法让Ruby用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. 我有一个正在编写的程序,它为文本文件生成一个单词频率哈希,我想把结果放到一个HTML文件而不是打印到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. 我认为每个字符串都需要使用readlines()或其他东西包装在HTML段落标记中,但我无法弄明白。 Then, once I've wrapped the strings in HTML 2) I want to write to an empty HTML file. 然后,一旦我在HTML 2中包装字符串,我想写一个空的HTML文件。

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: 我想导出到包含以下行的HTML文件:

<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. 你可能想看看我开发的dom gem 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>"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM