Чтобы сгруппировать все разделы вместе, вы можете использовать функцию Python groupby()
.Для этого требуется функция, которая извлекает номер раздела из абзаца.Затем функция groupby создает список всех абзацев с одинаковым номером раздела и возвращает их вместе:
from itertools import groupby
import bs4 as bs
import urllib.request
def section(paragraph):
return paragraph.sectno.text.strip('§ ').split('.')[0]
source = urllib.request.urlopen('https://www.govinfo.gov/bulkdata/CFR/2018/title-49/CFR-2018-title49-vol1.xml/').read()
soup = bs.BeautifulSoup(source, 'lxml')
for section_number, paragraphs in groupby(soup.find_all('section'), section):
filename = f'Section {int(section_number):02}.txt'
with open(filename, 'w', encoding='utf-8') as f_output:
section_text = '\n-------------\n'.join(p.text for p in paragraphs)
f_output.write(section_text)
Здесь файлы будут выглядеть следующим образом:
Section 01.txt
Section 03.txt
Section 05.txt
Section 06.txt
Section 07.txt
Section 08.txt
...
Section 10.txt
Section 80.txt
Section 89.txt
Section 91.txt
Section 92.txt
Section 93.txt
Section 98.txt
Section 99.txt
Каждый абзац также разделенс маленькой строчкой.