Programming Freaks  | دورات ومقالات برمجيه

Please login or register.

Login with username, password and session length
Advanced search  

News:

Please Read our FAQ

Author Topic: HappyMapper (XML to Python)  (Read 972 times)

Striky

  • Helping Freak
  • Administrator
  • Posting Freak
  • *****
  • Posts: 252
    • View Profile
    • WWW
    • Email
HappyMapper (XML to Python)
« on: December 27, 2008, 02:24:04 AM »
ضع فى حسبانك ملف كالتالى
Code: [Select]
<?xml version="1.0"?>
<computer>
<library>
<books>
    <book id="1">
        <name>Introduction to Python</name>
        <author>Ahmed Youssef</author>
        <price>80</price>
    </book>
    <book id="2">
        <name>Introduction to Java</name>
        <author>Wael Muhammed</author>
        <price>130</price>
    </book>
    <book id="3">
        <name>Introduction to Ruby</name>
        <author>Ahmed Youssef</author>
        <price>70</price>
    </book>
    <book id="4">
    <name>Introduction to Linux Programming</name>
    <author>Ahmed Mostafa</author>
    <price>90</price>
    </book>
</books>
</library>
</computer>
 

فاكر الموضوع الممل عن معالجة ملفات ال XML فى بايثون ؟
http://programming-fr34ks.net/smf/articles-12/xmling-with-python/
 DOM, SAX وكلام كتير مارأيك فى هذا الكود ؟
Code: [Select]
     for book in computer.library.books:
        print book.id,  book.name, ", by ", book.author

    totalsum=sum([int(str(book.price)) for book in computer.library.books])
    print "SUM: ", totalsum

مش اسهل بكتير ؟
الناتج
Code: [Select]
 1 Introduction to Python , by  Ahmed Youssef
2 Introduction to Java , by  Wael Muhammed
3 Introduction to Ruby , by  Ahmed Youssef
4 Introduction to Linux Programming , by  Ahmed Mostafa
SUM:  370


ماذا عن ال attributes ؟
تستطيع الوصول اليها ايضا من خلال اسمها مباشرة

او ملف من amazon مشابه للتالى
Code: [Select]
<?xml version="1.0" encoding="UTF-8"?>
<ItemSearchResponse xmlns="http://webservices.amazon.com/AWSECommerceService/2005-10-05">
    <OperationRequest>
        <HTTPHeaders>
            <Header Name="UserAgent">
            </Header>
        </HTTPHeaders>
        <RequestId>16WRJBVEM155Q026KCV1</RequestId>
        <Arguments>
            <Argument Name="SearchIndex" Value="Books"></Argument>
            <Argument Name="Service" Value="AWSECommerceService"></Argument>
            <Argument Name="Title" Value="Ruby on Rails"></Argument>
            <Argument Name="Operation" Value="ItemSearch"></Argument>
            <Argument Name="AWSAccessKeyId" Value="dontbeaswoosh"></Argument>
        </Arguments>
        <RequestProcessingTime>0.064924955368042</RequestProcessingTime>
    </OperationRequest>
    <Items>
        <Request>
            <IsValid>True</IsValid>
            <ItemSearchRequest>
                <SearchIndex>Books</SearchIndex>
                <Title>Ruby on Rails</Title>
            </ItemSearchRequest>
        </Request>
        <TotalResults>22</TotalResults>
        <TotalPages>3</TotalPages>
        <Item>
            <ASIN>0321480791</ASIN>
        <DetailPageURL>http://www.amazon.com/gp/redirect.html%3FASIN=0321480791%26tag=ws%26lcode=xm2%26cID=2025%26ccmID=165953%26location=/o/ASIN/0321480791%253FSubscriptionId=dontbeaswoosh</DetailPageURL>
            <ItemAttributes>
                <Author>Michael Hartl</Author>
                <Author>Aurelius Prochazka</Author>
                <Manufacturer>Addison-Wesley Professional</Manufacturer>
                <ProductGroup>Book</ProductGroup>
                <Title>RailsSpace: Building a Social Networking Website with Ruby on Rails (Addison-Wesley Professional Ruby Series)</Title>
            </ItemAttributes>
        </Item>
    </Items>
</ItemSearchResponse>
 

وتريد الحصول على بعض العناصر اليس كذلك ؟
Code: [Select]
    print rt.OperationRequest.HTTPHeaders.Header.Name
    print rt.OperationRequest.Arguments[0].Name
    print rt.OperationRequest.RequestProcessingTime
    print rt.Items.TotalPages
    print rt.Items.TotalResults
    print rt.Items.Item.ASIN
    print rt.Items.Item.DetailPageURL

اليس اسهل كثيرا ؟
Code: [Select]
UserAgent
SearchIndex
0.064924955368042
3
22
0321480791
http://www.amazon.com/gp/redirect.html%3FASIN=0321480791%26tag=ws%26lcode=xm2%26cID=2025%26ccmID=165953%26location=/o/ASIN/0321480791%253FSubscriptionId=dontbeaswoosh


 

او ربما مهتم ب Twitter ؟
على فرض لدينا هذا الملف
Code: [Select]
<?xml version="1.0" encoding="UTF-8"?>
<statuses type="array">
  <status>
    <created_at>Sat Aug 09 05:38:12 +0000 2008</created_at>
    <id>882281424</id>
    <text>I so just thought the guy lighting the Olympic torch was falling when he began to run on the wall. Wow that would have been catastrophic.</text>
    <source>web</source>
    <truncated>false</truncated>
    <in_reply_to_status_id>1234</in_reply_to_status_id>
    <in_reply_to_user_id>12345</in_reply_to_user_id>
    <favorited></favorited>
    <user>
      <id>4243</id>
      <name>John Nunemaker</name>
      <screen_name>jnunemaker</screen_name>
      <location>Mishawaka, IN, US</location>
      <description>Loves his wife, ruby, notre dame football and iu basketball</description>
      <profile_image_url>http://s3.amazonaws.com/twitter_production/profile_images/53781608/Photo_75_normal.jpg</profile_image_url>
      <url>http://addictedtonew.com</url>
      <protected>false</protected>
      <followers_count>486</followers_count>
    </user>
  </status>
</statuses>

وتريد الحصول على كل ماتحت ال user
Code: [Select]
    statuses.status.user.inspect_me() 


ستجد الناتج
Code: [Select]
Attrs: 
Tags:
id  =>  4243
name  =>  John Nunemaker
screen_name  =>  jnunemaker
location  =>  Mishawaka, IN, US
description  =>  Loves his wife, ruby, notre dame football and iu basketball
profile_image_url  =>  http://s3.amazonaws.com/twitter_production/profile_images/53781608/Photo_75_normal.jpg
url  =>  http://addictedtonew.com
protected  =>  false
followers_count  =>  486


اكيد مازالت تحتاج للعديد من الإختبارات وبإستخدامك هيتم تحسينها

كيفية الإستخدام
1- استدعاء happymapper


2- استخدام الدالة get_root اللتى تأخذ معامل xmlfile وهو مسار ملف الxml وتعيد لك ال root tag
Code: [Select]
def testGetRoot():
    computer=get_root("books.xml")
    print computer.library.books[0].name

طيب دا بالنسبة للملفات الخارجية ماذا عن النصوص الداخلية ؟ قرأت الصفحة فى متغير داخلى او ماشابه ماذا تفعل ؟
تستطيع استخدام الدالة get_root_document التى تأخذ معامل doc وهو محتوى ملف XML وتعيد لك ال root tag

ملحوظة الملفات المستخدمة فى الشرح amazon.xml و twitter.xml مأخوذه من هنا
http://railstips.org/2008/11/17/happymapper-making-xml-fun-again

وبس كدا :)

للتحميل
http://programming-fr34ks.net/pfsoft/happymapperstable.tar.gz

« Last Edit: March 25, 2009, 11:17:18 PM by Ahmed Youssef »
Logged

Life is just a chance to grow a soul. - A. Powell
Weblog: http://ahmedyoussef.wordpress.com/

Striky

  • Helping Freak
  • Administrator
  • Posting Freak
  • *****
  • Posts: 252
    • View Profile
    • WWW
    • Email
Re: HappyMapper (XML to Python)
« Reply #1 on: March 25, 2009, 11:17:56 PM »


الإصدار الجديد من HappyMapper مش فيه حاجات كتير غير تدعيم البحث وامكانية التصفح الملف عن طريق prevSib, nextSib مع دعم اساسى لملفات ال HTML معتمد على  HTMLParser

مثال
Code: [Select]
def simple_xml_test():
    txt="""<?xml version="1.0"?>
<computer>
    <library>
        <books>
            <book id="1" class="programming">
                <name>Introduction to Python</name>
                <author>Ahmed Youssef</author>
                <price>80</price>
            </book>
            <book id="2" class="programming">
                <name>Introduction to Java</name>
                <author>Wael Muhammed</author>
                <price>130</price>
            </book>
            <book id="3" class="programming">
                <name>Introduction to Ruby</name>
                <author>Ahmed Youssef</author>
                <price>70</price>
            </book>
            <book id="4" class="programming">
            <name>Introduction to Linux Programming</name>
            <author>Ahmed Mostafa</author>
            <price>90</price>
            </book>
        </books>
    </library>
</computer>
"""
    root=get_root_document(txt)
    print root.prettify()
    bookslist=list(book.name.content for book in find_all("book", root))
    print bookslist
    total=sum(list(int(price.clean_content) for price in find_all("price", root)))
    print "TOTAL: ", total


للحصول على ال root للملف استخدم get_root_document “اذا كان string” كما فى المثال او استخدم get_root على ملف ما
تقدر فى اى وقت تستدعى inspect_all على ال root او اى tag لترى المعلومات حوله مثل السابق والتالى والأب
ولطباعة الملف بصورة "شيك" تقدر تستدعى prettify

وللبحث عن عنصر من عناصر الملف استخدم find_all .. كما فى المثال
Code: [Select]
    bookslist=list(book.name.content for book in find_all("book", root)) 

هنا حصلنا على كل العناصر المسماه ب book ووصلنا للعنصر name بداخلها ومنها content للحصول على محتواه
للحصول على مجموع الأسعار
Code: [Select]
     total=sum(list(int(price.clean_content) for price in find_all("price", root)))



ناتج التنفيذ
Code: [Select]
 [u'Introduction to Python', u'Introduction to Java', u'Introduction to Ruby', u'Introduction to Linux Programming']

TOTAL:  370


تقدر توصله هنا
http://programming-fr34ks.net/pfsoft/happymapper7.py

« Last Edit: March 25, 2009, 11:40:51 PM by Ahmed Youssef »
Logged

Life is just a chance to grow a soul. - A. Powell
Weblog: http://ahmedyoussef.wordpress.com/