Python Beautifulsoup:获取每个单词的类名

Python Beautifulsoup:获取每个单词的类名,python,html,beautifulsoup,Python,Html,Beautifulsoup,我试图创建一个函数,告诉我文本中每个单词的标记类 我的html是这样的: <p> <span class="A">I am </span> <span class="B"><span class="C"> not </span> doing a great job </span> </p> 我尝试用FindAll('span',recursive=False)循环所有跨度,并检查每个跨度是否有子跨度

我试图创建一个函数,告诉我文本中每个单词的标记类

我的html是这样的:

<p>
<span class="A">I am </span>
<span class="B"><span class="C"> not </span> doing a great job </span>
</p>
我尝试用FindAll('span',recursive=False)循环所有跨度,并检查每个跨度是否有子跨度,但我总是得到双跨度。 例如,我会得到“没有做好工作”和“没有”

我已经看过了文档,但是我似乎没有找到任何方法可以让我得到文本和它周围的直接跨度

提前感谢您的帮助,
类属性

您可以通过
查找所有(text=True)
在文本节点上进行迭代,然后进入树并获取一个:

[["I", A], ["am", A], ["not", C], ["doing", B], ["a", B], ["great", B], ["job", B]]
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])
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']]