【问题标题】:Beautifulsoup: get class name for each wordBeautifulsoup:获取每个单词的类名
【发布时间】:2016-05-18 13:48:40
【问题描述】:

我正在尝试创建一个函数来告诉我文本中每个单词的标签类别。

我的 html 是这样的:

<p>
<span class="A">I am </span>
<span class="B"><span class="C"> not </span> doing a great job </span>
</p>

所以我想创建一个返回列表的函数:

[["I", A], ["am", A], ["not", C], ["doing", B], ["a", B], ["great", B], ["job", B]]

我尝试使用 FindAll('span', recursive=False) 循环所有跨度,并检查每个跨度是否有孩子,但我总是得到双打。 例如,我会得到“做得不好”和“不好”。

for p in p_tags:
  my_tag_list = []
  spans = p.findAll("span", recursive=False)
  for s in spans:
    text = s.text.split()
    for t in text:
       my_tag = []
       my_tag.append(t)
       my_tag.append(s["class"][0])

我查看了文档,但似乎没有找到任何方法可以让我获得文本及其周围的直接跨度。

提前感谢您的帮助, 亲切的问候

【问题讨论】:

    标签: python html beautifulsoup


    【解决方案1】:

    您可以通过find_all(text=True) 遍历文本节点,上树并获取.parent 的类属性:

    from bs4 import BeautifulSoup
    
    data = """
    <p>
    <span class="A">I am </span>
    <span class="B"><span class="C"> not </span> doing a great job </span>
    </p>"""
    
    soup = BeautifulSoup(data, "html.parser")
    
    result = []
    for text in soup.p.find_all(text=True):
        parent = text.parent
        parent_class = parent["class"][0] if "class" in parent.attrs else ""
        for word in text.split():
            result.append([word, parent_class])
    
    print(result)
    

    打印:

    [[u'I', u'A'], [u'am', u'A'], [u'not', u'C'], [u'doing', u'B'],
     [u'a', u'B'], [u'great', u'B'], [u'job', u'B']]
    

    【讨论】:

      猜你喜欢
      • 2020-08-19
      • 2017-06-11
      • 2013-10-07
      • 2011-08-20
      • 2018-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多