Best way to parse a table in Ruby

I would like to analyze a simple table in a Ruby data structure. The table looks like this:

alt text http://img232.imageshack.us/img232/446/picture5cls.png http://img232.imageshack.us/img232/446/picture5cls.png

Edit: Here is the HTML

and I would like to parse it into an hash array .. For example,

schedule[0]['NEW HAVEN'] == '4:12AM'
schedule[0]['Travel Time In Minutes'] == '95'

Any thoughts on how to do this? Perl has HTML :: TableExtract , which I think would do the job, but I can't find a similar library for Ruby.

+3
source share
2 answers

Hpricot (gem install hpricot, sudo * nix )

HTML input.html, :

require 'hpricot'

doc = Hpricot.XML(open('input.html'))

table = doc/:table

(table/:tr).each do |row|
  (row/:td).each do |cell|
    puts cell.inner_html
  end
end

<span class="black">12:17AM </span>
<span class="black">
    <a href="http://www.mta.info/mnr/html/planning/schedules/ref.htm"></a></span>
<span class="black">1:22AM  </span>
<span class="black">
    <a href="http://www.mta.info/mnr/html/planning/schedules/ref.htm"></a></span>
<span class="black">65</span>
<span class="black">TRANSFER AT STAMFORD (AR 1:01AM & LV 1:05AM)                                                                            </span>
<span class="black">

 N


</span>

, TD. , .

(BTW, HTML : <th> <tbody>, : <tbody> , <table>. , <tr><th>...</th></tr> <thead> . "" HTML, !)

+5

, ruby ​​ , , :

require 'nokogiri'
doc=Nokogiri("<table><tr><th>la</th><th><b>lu</b></th></tr><tr><td>lala</td><td>lulu</td></tr><tr><td><b>lila</b></td><td>lolu</td></tr></table>")
header, *rest = (doc/"tr").map do |row|
  row.children.map do |c|
    c.text
  end
end
header.map! do |str| str.to_sym end
item_struct = Struct.new(*header)
table = rest.map do |row|
  item_struct.new(*row)
end
table[1].lu #=> "lolu"

, , .

+2

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


All Articles