Beautifulsoup:获取每个单词的类名

2024-05-13 12:51:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个函数,它将告诉我文本中每个单词的标记类。在

我的html是这样的:

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

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

^{pr2}$

我尝试过用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])

我已经看过文档,但是我似乎没有找到任何方法来获得文本和它周围的直接跨度。在

提前感谢您的帮助, 谨致问候


Tags: 函数textin文本falseformytag
1条回答
网友
1楼 · 发布于 2024-05-13 12:51:03

您可以通过find_all(text=True)遍历文本节点,进入树并获得^{}的class属性:

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)

印刷品:

^{pr2}$

相关问题 更多 >