اذهب إلى المحتوى
  • 0

تحويل بنية XML إلى DataFrame باستخدام BeautifulSoup في بايثون

إياد أحمد

السؤال

لدي ملف XML وأحتاج إلى تحويله إلى DataFrame لإجراء بعض العمليات عليه، فكيف يمكننا القيام بذلك؟
هذه هي محتويات الملف:

<?xml version="1.0"?>
<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications with XML.</description>
   </book>
   <book id="bk102">
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-12-16</publish_date>
      <description>A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world.</description>
   </book>
   <book id="bk103">
      <author>Corets, Eva</author>
      <title>Maeve Ascendant</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-11-17</publish_date>
      <description>After the collapse of a nanotechnology society in England, the young survivors lay the foundation for a new society.</description>
   </book>
   <book id="bk104">
      <author>Corets, Eva</author>
      <title>Oberon's Legacy</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2001-03-10</publish_date>
      <description>In post-apocalypse England, the mysterious agent known only as Oberon helps to create a new life for the inhabitants of London. Sequel to Maeve Ascendant.</description>
   </book>
   <book id="bk105">
      <author>Corets, Eva</author>
      <title>The Sundered Grail</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2001-09-10</publish_date>
      <description>The two daughters of Maeve, half-sisters, battle one another for control of England. Sequel to Oberon's Legacy.</description>
   </book>
   <book id="bk106">
      <author>Randall, Cynthia</author>
      <title>Lover Birds</title>
      <genre>Romance</genre>
      <price>4.95</price>
      <publish_date>2000-09-02</publish_date>
      <description>When Carla meets Paul at an ornithology conference, tempers fly as feathers get ruffled.</description>
   </book>
   <book id="bk107">
      <author>Thurman, Paula</author>
      <title>Splish Splash</title>
      <genre>Romance</genre>
      <price>4.95</price>
      <publish_date>2000-11-02</publish_date>
      <description>A deep sea diver finds true love twenty thousand leagues beneath the sea.</description>
   </book>
   <book id="bk108">
      <author>Knorr, Stefan</author>
      <title>Creepy Crawlies</title>
      <genre>Horror</genre>
      <price>4.95</price>
      <publish_date>2000-12-06</publish_date>
      <description>An anthology of horror stories about roaches,centipedes, scorpions  and other insects.</description>
   </book>
   <book id="bk109">
      <author>Kress, Peter</author>
      <title>Paradox Lost</title>
      <genre>Science Fiction</genre>
      <price>6.95</price>
      <publish_date>2000-11-02</publish_date>
      <description>After an inadvertant trip through a Heisenberg Uncertainty Device, James Salway discovers the problems of being quantum.</description>
   </book>
   <book id="bk110">
      <author>O'Brien, Tim</author>
      <title>Microsoft .NET: The Programming Bible</title>
      <genre>Computer</genre>
      <price>36.95</price>
      <publish_date>2000-12-09</publish_date>
      <description>Microsoft's .NET initiative is explored in detail in this deep programmer's reference.</description>
   </book>
   <book id="bk111">
      <author>O'Brien, Tim</author>
      <title>MSXML3: A Comprehensive Guide</title>
      <genre>Computer</genre>
      <price>36.95</price>
      <publish_date>2000-12-01</publish_date>
      <description>The Microsoft MSXML3 parser is covered in detail, with attention to XML DOM interfaces, XSLT processing, SAX and more.</description>
   </book>
   <book id="bk112">
      <author>Galos, Mike</author>
      <title>Visual Studio 7: A Comprehensive Guide</title>
      <genre>Computer</genre>
      <price>49.95</price>
      <publish_date>2001-04-16</publish_date>
      <description>Microsoft Visual Studio 7 is explored in depth,looking at how Visual Basic, Visual C++, C#, and ASP+ are integrated into a comprehensivedevelopment environment.</description>
   </book>
</catalog>


 

رابط هذا التعليق
شارك على الشبكات الإجتماعية

Recommended Posts

  • 1

بشكل عام يمكنك القيام بالخطوات التالية للإمساك بأي ملف XML وتحويله ل DF:

# استيراد الوحدات اللازمة
from bs4 import BeautifulSoup
import pandas as pd
# xml قراءة ملف ال
contents = open("file.xml",'r').read()
# BeautifulSoup تحليل الملف الذي تم الحصول عليه من خلال 
soup = BeautifulSoup(contents, 'lxml')
# find_all الآن نقوم باستخراج البيانات حيث نستخدم الدالة 
# التي تُرجع البيانات المستخرجة الموجودة داخل الوسم الذي يتم تمريره لها  
authors = soup.find_all('author')
pubdate = soup.find_all('publish_date')
genres = soup.find_all('genre')
des = soup.find_all('description')
titles = soup.find_all('title')
prices = soup.find_all('price')
# xml الآن ، لدينا جميع البيانات المستخرجة من ملف
# نحتاج الآن إلى دمج جميع البيانات المتعلقة بكتاب واحد من قوائم مختلفة
# لذا سوف نستخدم حلقة 
# rows حيث يتم تخزين جميع بيانات كتاب معين من قوائم مختلفة في  قائمة واحدة 
# data ثم يتم إضاقة كل صف في قائمة أخرى هي 
# كما يلي
data = []
for i in range(0,len(authors)):
		rows = [authors[i].get_text(),titles[i].get_text(),
		genres[i].get_text(),prices[i].get_text(),
		pubdate[i].get_text(),des[i].get_text()]
data.append(rows)
# وأخيراً سنشكل الداتافريم
df = pd.DataFrame(data,columns = ['Author','Book Title',
								 'Genre','Price','Publish Date',
								 'Description'])

 

رابط هذا التعليق
شارك على الشبكات الإجتماعية

  • 1

يمكنك إستخراج البيانات بشكل بسيط ومرتب من خلال تحديد كل الكتب ثم المرور على كل كتاب وإستخراج بياناته، كالتالي:

from bs4 import BeautifulSoup
import pandas as pd

content = open("books.xml",'r', encoding="utf-8").read()
soup = BeautifulSoup(content, features='lxml')

# هنا سيتم تخزين بيانات كل كتاب
data = []

# نحدد كل الكتب
books = soup.find_all('book')


# الآن نقوم بالمرور على كل كتاب وتخزين بياناته في القائمة data
for book in books:
    book_d = {}	# بيانات الكتاب الواحد
    book_d['author'] =  book.find('author').get_text()
    book_d['title'] =  book.find('title').get_text()
    book_d['genre'] =  book.find('genre').get_text()
    book_d['price'] =  book.find('price').get_text()
    book_d['publish_date'] =  book.find('publish_date').get_text()
    book_d['description'] =  book.find('description').get_text()

    data.append(book_d)


# الآن نقوم بتحويل القائمة data إلى dataFrame
df = pd.DataFrame(data)	# لا نحتاج إلى تحديد الأعمدة لأننا أستخدمنا قائمة من القواميس dictionaries
print(df)

وستكون النتيجة كالتالي:
 

                  author                                   title            genre  price publish_date                                        description
0   Gambardella, Matthew                   XML Developer's Guide         Computer  44.95   2000-10-01  An in-depth look at creating applications with...
1             Ralls, Kim                           Midnight Rain          Fantasy   5.95   2000-12-16  A former architect battles corporate zombies, ...
2            Corets, Eva                         Maeve Ascendant          Fantasy   5.95   2000-11-17  After the collapse of a nanotechnology society...
3            Corets, Eva                         Oberon's Legacy          Fantasy   5.95   2001-03-10  In post-apocalypse England, the mysterious age...
4            Corets, Eva                      The Sundered Grail          Fantasy   5.95   2001-09-10  The two daughters of Maeve, half-sisters, batt...
5       Randall, Cynthia                             Lover Birds          Romance   4.95   2000-09-02  When Carla meets Paul at an ornithology confer...
6         Thurman, Paula                           Splish Splash          Romance   4.95   2000-11-02  A deep sea diver finds true love twenty thousa...
7          Knorr, Stefan                         Creepy Crawlies           Horror   4.95   2000-12-06  An anthology of horror stories about roaches,c...
8           Kress, Peter                            Paradox Lost  Science Fiction   6.95   2000-11-02  After an inadvertant trip through a Heisenberg...
9           O'Brien, Tim   Microsoft .NET: The Programming Bible         Computer  36.95   2000-12-09  Microsoft's .NET initiative is explored in det...
10          O'Brien, Tim           MSXML3: A Comprehensive Guide         Computer  36.95   2000-12-01  The Microsoft MSXML3 parser is covered in deta...
11           Galos, Mike  Visual Studio 7: A Comprehensive Guide         Computer  49.95   2001-04-16  Microsoft Visual Studio 7 is explored in depth...

 

رابط هذا التعليق
شارك على الشبكات الإجتماعية

انضم إلى النقاش

يمكنك أن تنشر الآن وتسجل لاحقًا. إذا كان لديك حساب، فسجل الدخول الآن لتنشر باسم حسابك.

زائر
أجب على هذا السؤال...

×   لقد أضفت محتوى بخط أو تنسيق مختلف.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   جرى استعادة المحتوى السابق..   امسح المحرر

×   You cannot paste images directly. Upload or insert images from URL.

  • إعلانات

  • تابعنا على



×
×
  • أضف...