Beautiful Soup: отделение элемента span от элемента p - PullRequest
1 голос
/ 03 августа 2020

Мне нужно вытащить элемент span из моего общего элемента p

Вот конкретный c пример одного из элементов p, которые я анализирую

<p id="p-9">
   <span class="inline-l2-heading">H5N1 virus pathogenic phenotypes among 
          inbred mouse strains.
   </span>
   We experimentally inoculated 21 mouse strains with the highly 
   pathogenic H5N1 influenza A virus A/Hong Kong/213/03 (HK213) 
   and monitored the animals for 30 days thereafter for signs of
   morbidity and mortality. The 50% mouse lethal dose (MLD<sub>50</sub>) 
   values varied from 40 50% egg infective doses (EID<sub>50</sub>) 
   for the influenza virus-susceptible strain DBA/2<sub>S</sub> 
   (susceptibility indicated by “S”) to more than 10<sup>6</sup> 
   EID<sub>50</sub> for the influenza virus-resistant strains 
   BALB/c<sub>R</sub> and BALB/cBy<sub>R</sub> 
   (resistance indicated by “R”) (<a class="xref-fig" href="#F1" id="xref-fig-1- 
   1">Fig. 1</a>).
</p>

Если я должны были взять абзац переменной как bs4.element.Tag и сделать это

print(paragraph.text)

Результат:

H5N1 virus pathogenic phenotypes among inbred mouse strains.We experimentally
inoculated 21 mouse strains with the highly pathogenic H5N1 influenza A virus
A/Hong Kong/213/03 (HK213) and monitored the animals for 30 days thereafter 
for signs of morbidity and mortality. The 50% mouse lethal dose (MLD50) 
values varied from 40 50% egg infective doses (EID50) for the influenza 
virus-susceptible strain DBA/2S (susceptibility indicated by “S”) to more 
than 106 EID50 for the influenza virus-resistant strains BALB/cR and 
BALB/cByR (resistance indicated by “R”) (Fig. 1).

Как вы можете видеть в первом и втором предложениях, это не так. t создать пробел между текстом в промежутке и текстом в остальной части абзаца.

В итоге получается что-то вроде:

«Патогенез вируса H5N1 c фенотипы среди инбредных мышей напряжений.Мы экспериментально ... "

Как видите, это приводит к тому, что в двух отдельных предложениях нет пробела после точки, что очень важно, так как позже я буду разбивать предложения по предложениям, и большинство разделителей предложений разделяются точкой и пробелом, а большинство других моих предложений сформированы правильно.

Есть ли способ, которым я могу отделить текст в диапазоне от остального текста с помощью bs4, а затем объединить их вместе послесловие с правильным интервалом?

Ответы [ 3 ]

1 голос
/ 03 августа 2020

Другое решение:

import re
from bs4 import BeautifulSoup


txt = '''<p id="p-9">
   <span class="inline-l2-heading">H5N1 virus pathogenic phenotypes among
          inbred mouse strains.
   </span>
   We experimentally inoculated 21 mouse strains with the highly
   pathogenic H5N1 influenza A virus A/Hong Kong/213/03 (HK213)
   and monitored the animals for 30 days thereafter for signs of
   morbidity and mortality. The 50% mouse lethal dose (MLD<sub>50</sub>)
   values varied from 40 50% egg infective doses (EID<sub>50</sub>)
   for the influenza virus-susceptible strain DBA/2<sub>S</sub>
   (susceptibility indicated by “S”) to more than 10<sup>6</sup>
   EID<sub>50</sub> for the influenza virus-resistant strains
   BALB/c<sub>R</sub> and BALB/cBy<sub>R</sub>
   (resistance indicated by “R”) (<a class="xref-fig" href="#F1" id="xref-fig-1-
   1">Fig. 1</a>).
</p>'''

soup = BeautifulSoup(txt, 'html.parser')
paragraph = soup.select_one('p')

# add space at the end of each span:
for span in paragraph.select('span'):
    span.append(BeautifulSoup('&nbsp;', 'html.parser'))

# post-process the text:
print(re.sub(r'\s{2,}', ' ', paragraph.text).strip())

Печать:

H5N1 virus pathogenic phenotypes among inbred mouse strains. We experimentally inoculated 21 mouse strains with the highly pathogenic H5N1 influenza A virus A/Hong Kong/213/03 (HK213) and monitored the animals for 30 days thereafter for signs of morbidity and mortality. The 50% mouse lethal dose (MLD50) values varied from 40 50% egg infective doses (EID50) for the influenza virus-susceptible strain DBA/2S (susceptibility indicated by “S”) to more than 106 EID50 for the influenza virus-resistant strains BALB/cR and BALB/cByR (resistance indicated by “R”) (Fig. 1).
0 голосов
/ 03 августа 2020

Попробуйте:

import re
from bs4 import BeautifulSoup
html = '''
<p id="p-9">
   <span class="inline-l2-heading">H5N1 virus pathogenic phenotypes among 
          inbred mouse strains.
   </span>
   We experimentally inoculated 21 mouse strains with the highly 
   pathogenic H5N1 influenza A virus A/Hong Kong/213/03 (HK213) 
   and monitored the animals for 30 days thereafter for signs of
   morbidity and mortality. The 50% mouse lethal dose (MLD<sub>50</sub>) 
   values varied from 40 50% egg infective doses (EID<sub>50</sub>) 
   for the influenza virus-susceptible strain DBA/2<sub>S</sub> 
   (susceptibility indicated by “S”) to more than 10<sup>6</sup> 
   EID<sub>50</sub> for the influenza virus-resistant strains 
   BALB/c<sub>R</sub> and BALB/cBy<sub>R</sub> 
   (resistance indicated by “R”) (<a class="xref-fig" href="#F1" id="xref-fig-1- 
   1">Fig. 1</a>).
</p>
'''

soup = BeautifulSoup(html, 'lxml')

p = soup.select('p')

for text in p:
    para = text.get_text(' ').replace('\n','')
para = re.sub(' +', ' ', para)
print(para.strip())

распечатает:

H5N1 virus pathogenic phenotypes among inbred mouse strains. We experimentally inoculated 21 mouse...

и так далее ..

0 голосов
/ 03 августа 2020

Я предполагаю, что вы используете get_result(). Вы можете сделать альтернативу в bs4 под названием strings. Это дает массив всех строк в супе. Затем вы можете join их вместе, чтобы получить правильно отформатированный текст:

from bs4 import BeautifulSoup

html_doc = """
<p>
    <span>Some Text.</span>
    Some text and probably other stuff.
</p>
"""
soup = BeautifulSoup(html_doc, 'html.parser')

print(" ".join(soup.strings))
print(" ".join(soup.stripped_strings))

Кроме того, я вижу в вашем примере у вас много пробелов для форматирования. Вы можете избавиться от них, набрав stripped_strings вместо

...