美丽汤 根据类型提取内容



我想从以下xml格式中提取问题(类型='q'(和答案(type='a'(对作为单个数据点:

<?xml version="1.0" encoding="us-ascii"?>
<transcript id="001" >
<body>
<section name="Q&amp;A">
<speaker id="0">
<plist>
<p>Thank you. We'll now be conducting the question-and-answer session. <mark type="Operator Instructions" /> Thank you. Please go ahead with your question.</p>
</plist>
</speaker>
<speaker id="3" type="q">
<plist>
<p>Good morning. First of all, Happy New Year.</p>
</plist>
</speaker>
<speaker id="2" type="a">
<plist>
<p>Happy New Year, sir.</p>
</plist>
</speaker>
<speaker id="3" type="q">
<plist>
<p>Thank you. How is your pain now?.</p>
</plist>
</speaker>
<speaker id="2" type="a">
<plist>
<p>Oh, it's better now. I think i am healing.</p>
</plist>
</speaker>
</section>
</body>
</transcript>

即输出应该是这样的:['早上好。首先,新年快乐。新年快乐,先生,"谢谢。你现在疼得怎么样?哦,现在好多了。我想我正在痊愈。

谁能帮我用美丽的汤来做这件事?我当前的代码提取了文档中的所有<p>标签,但问题是还有其他部分("Q&A"除外(,其<p>标签也被提取。

soup = BeautifulSoup(handler, "html.parser")
texts = []
for node in soup.findAll('p'):
text = " ".join(node.findAll(text=True))
#text = clean_text(text)
texts.append(text)

您可以分别使用find_all('speaker', type='q')find_all('speaker', type='a')找到所有问题和所有答案。然后使用zip连接相应的问题及其答案。

法典:

questions = soup.find_all('speaker', type='q')
answers = soup.find_all('speaker', type='a')
for q, a in zip(questions, answers):
print(' '.join((q.p.text, a.p.text)))

输出:

Good morning. First of all, Happy New Year. Happy New Year, sir.
Thank you. How is your pain now?. Oh, it's better now. I think i am healing.

如果你想在列表中使用它,你可以使用列表推导:

q_and_a = [' '.join((q.p.text, a.p.text)) for q, a in zip(questions, answers)]
print(q_and_a)
# ['Good morning. First of all, Happy New Year. Happy New Year, sir.',
#  "Thank you. How is your pain now?. Oh, it's better now. I think i am healing."]

您可以使用findAll('speaker', {"type": "q"})查找问题,并使用findNext("speaker")查找相应的答案。

前任:

from bs4 import BeautifulSoup
soup = BeautifulSoup(handler, "html.parser")
for node in soup.findAll('speaker', {"type": "q"}):
print( node.find("p").text )
print( node.findNext("speaker").find("p").text)
print( "--" )

输出:

Good morning. First of all, Happy New Year.
Happy New Year, sir.
--
Thank you. How is your pain now?.
Oh, it's better now. I think i am healing.
--

最新更新