0

私はプログラムを持っていますが、クラスの概念を含まないもの(Pythonプログラムはクラスの概念に何らかの価値を持っています)は、Pythonの世界では本当に新しいものです。ですから、元の方法から学ぶことは、私がこの世界で輝くのを助けてくれます。この質問を否定的なマークにする代わりに、誰かが親切に私を助けてくれますか:(

 import xml.etree.ElementTree as ET
 import sys

doc       = ET.parse("books.xml")
root      = doc.getroot() 
root_new  = ET.Element("books") 
for child in root:
    name                = child.attrib['name']
    cost                = child.attrib['cost']
    # create "book" here
    book    = ET.SubElement(root_new, "book") 
    book.set("name",name)               
    book.set("cost",cost) 
    if 'color' in child.attrib:
        color               = child.attrib['color']
        book.set("color",color) 
    if 'weight' in child.attrib:
        weight              = child.attrib['weight']
        book.set("weight",weight)
    for g in child.findall("cover"):
        # create "group" here
       cover     = ET.SubElement(cover,"cover")  
        if g.text != "goldcover":
            cover.text = g.text 
tree = ET.ElementTree(root_new)
tree.write(sys.stdout)

理解のために:私のxmlは、

<books>
<book name="goodbook" cost="10" color="green"></book>
<book name="badbook" cost="1000" weight="100"><cover>papperback</cover><cover>hardcover</cover></book>
<book name="avgbook" cost="99" weight="120"></book>
</books>

Pythonの新入生として、誰かが私を助けてくれることを願っています。すべての貴重な入力を温かく歓迎します。

4

1 に答える 1

5

さて、これはそれほど難しい練習ではありませんが、私はこの方法でこれを行います。あなたは本のコレクションを持っているので、私のクラスが呼び出さBookCollectionれ、XMLファイルへのパスを取ります。

ここで必要なのはparse、XMLへのメソッドget、本へのメソッド、および本へのメソッドsetです。したがって、スケルトンクラスは次のようになります。

class BookCollection( object ):
    def __init__( self, xml_path ):
        """call the parse with the xml_path here"""
        self.bookList = []#This is a list of tuples

    def _parse( self, xml_path ):
        """This method is private and only parses the 
           xml and stores the books as tuples in a list"""

    def get( self, title ):
        """This method allows the user of this class to get 
           a book from the list of tuples"""

    def _set( self, title, cost, weight, cover=None ):
        """This method sets and adds a book tuple to the 
           list of book tuples"""

本をPythonのクラスとして表す必要はありません。これは、コードのビット全体、つまりタプルを非常に複雑にするためです。そして、なぜ私はXMLファイルを本のコレクションとして抽象化したのか。

スケルトン以外の詳細は入力しないので、そこから残りの部分を学ぶことができます。

編集:XMLも出力したいようですがto_xml、上記のクラスにXMLを書き出すメソッドを追加します。書籍を削除する必要がある場合は、関連するメソッドも追加しますが、実装する必要があります。

于 2012-11-06T05:56:08.193 に答える