Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extract all text within a tag & save to dictionary using beautifulSoup

I have an xml file that looks a bit like this:

<article id = '1'> 
  <p> This is </p> 
  <p> example A </p>
</article>

<article id = '2'> 
  <p> This is </p> 
  <p> example B </p>
</article>

I would like to create a dictionary that looks like this:

{1: 'This is example A', 2: 'This is example B'}

with the keys being the ‘id’ in the tag. What is the best way to go about doing this using beautiful soup?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This is how I will do it:

from bs4 import BeautifulSoup


output = {}

# If you're getting your XML file from the web skip this step:
with open("xml_file.xml", mode="r") as f:
    data = f.read()

soup = BeautifulSoup(data)
articles = soup.find_all('article')

for i in range(len(articles)):
    output[i+1] = ' '.join(articles[i].text.replace('\n', '').split())

Hope this helps!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading