当前位置 : 主页 > 编程语言 > ruby >

在Ruby中解析表的最佳方法

来源:互联网 收集:自由互联 发布时间:2021-06-23
我想将一个简单的表解析为 Ruby数据结构.该表如下所示: alt text http://img232.imageshack.us/img232/446/picture5cls.png http://img232.imageshack.us/img232/446/picture5cls.png 编辑:Here is the HTML 我想把它解析成
我想将一个简单的表解析为 Ruby数据结构.该表如下所示:

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

编辑:Here is the HTML

我想把它解析成一系列哈希.例如.,:

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

有关如何做到这一点的任何想法? Perl有HTML::TableExtract,我认为它可以完成这项工作,但我找不到任何类似的Ruby库.

您可能想尝试 Hpricot(gem install hpricot,为* nix系统添加常用的sudo)

我将您的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标签的内容了.还有一点工作,你就在那里.

(顺便说一下,HTML看起来有点格格不入:你在< tbody>中有< th>标签,这看起来有点反常:如果它只是< table>中的另一个级别,那么< tbody>是没有意义的.如果您的< tr>< th> …< / th>< / tr>内容在单独的< thead>部分within the table中,则更有意义.但它可能不是“您的”HTML,当然!)

网友评论