【问题标题】:How to find the structure of repeating elements in XML/HTML如何在 XML/HTML 中查找重复元素的结构
【发布时间】:2012-11-03 18:41:18
【问题描述】:

我目前正在尝试解决一个编程问题。我正在尝试在任何 HTML 页面中查找重复的结构,并且正在尝试检索这些元素的值。

例如,我有一个带有重复元素的 HTML 页面,如下所示:

<html>
<body>
  <ul>
     <li>green</li>
     <li>orange</li>
     <li>red</li>
  </ul>
</body>

在此代码中,我想检测是否存在重复块(“li”项),并且我想提取它们的值。另一个 HTML 示例:

<table>
   <tr>
      <td>1</td>
      <td>John</td>
   </tr>
   <tr>
      <td>2</td>
      <td>Simon</td>
   </tr>
</table>

在此示例中,我想检测结构是否重复,并从中获取值 [1,John] 和 [2,Simon]。

我的问题是:是否有一个简单的算法来做这样的事情,或者,如果没有,你会如何处理这样的事情?

【问题讨论】:

  • 你使用什么编程语言?
  • 您必须提供更多详细信息。在第二个示例中, 也被重复,因此提取 1 和 John 对我来说似乎也是一个有效的解决方案。重复元素也应该在没有中断的情况下跟随(例如,如果表格的两行之间有一些文本,我们仍然会对它们感兴趣。总的来说,你必须定义 repeating blocktheir values
  • 在定义repeating block时,还要说明不同嵌套级别的其他匹配块是否算匹配,重复块是否可以重叠等。
  • @Holf 我正在使用 Java,但我对这种方法比对实际代码更感兴趣。
  • @izomorphius 好收获!我想我正在寻找这个特定示例中最大的(以字符为单位的)重复结构块。所以 是一个重复块,而 是一个更大的重复块。

标签: string algorithm text


【解决方案1】:

一个相当基本的python程序,检测重复的tr-td-td标签序列和重复的td标签如下所示。将您的第二个 html 示例保存在文件 xml.html 中,程序会打印出:

tr.td.td 

td 1
td John
tr.td.td 

td 2
td Simon
Counter({'td': 4, 'tr.td.td': 2, 'table.tr.tr': 1})
#!/usr/bin/env python
from xml.etree import cElementTree as ET
from collections import Counter

def sot(r, depth):
    tags = r.tag
    for e in r.getchildren():
        tags += '.' + sot(e, depth+1)
    r.tail = tags
    cc[r.tail] += 1
    return r.tag

def tot(r, depth):
    if cc[r.tail] > 1:
        print r.tail, r.text
    for e in r.getchildren():
        tot(e, depth+1)

cc = Counter()
p=ET.parse ("xml.html")
sot(p.getroot(), 0)
tot(p.getroot(), 0)
print cc

【讨论】:

    猜你喜欢
    相关资源
    最近更新 更多
    热门标签