0

次の文字列があります。

"Sweden, Västmanland, Västerås" 
"Sweden, Dalarna, Leksand" 
"Ireland, Cork, Cobh"
"Ireland, Clare, Boston"
"Ireland, Cork, Baltimore"
"Sweden, Dalarna, Mora" 

次のようにxmlに変換したい:

<?xml version="1.0" ?> 
<data>
<country name = "Ireland">
    <region name = "Clare">
        <settlement name  = "Boston"/>
    </region>
    <region name = "Cork">
        <settlement name = "Baltimore"/>
        <settlement name = "Cobh"/>
    </region>
</country>

<country name = "Sweden">
    <region name = "Dalarna">
        <settlement name = "Leksand"/>
        <settlement name = "Mora"/>
    </region>
    <region name = "Västmanland">
        <settlement name = "Västerås"/>
    </region>
</country>
</data>

不必要に車輪を再発明するために、この変換を行うのに役立つpython3の組み込みライブラリは何ですか?

4

2 に答える 2

2
import xml.etree.ElementTree as ET
from collections import defaultdict

strings = ["Sweden, Västmanland, Västerås",
"Sweden, Dalarna, Leksand",
"Ireland, Cork, Cobh",
"Ireland, Clare, Boston",
"Ireland, Cork, Baltimore",
"Sweden, Dalarna, Mora"]

dd = defaultdict(lambda: defaultdict(list))

for s in strings:
    a, b, c = s.split(', ')
    dd[a][b].append(c)

root = ET.Element('data')

for c, regions in dd.items():
    country = ET.SubElement(root,  'country', {'name': c})
    for r, settlements in regions.items():
        region = ET.SubElement(country, 'region', {'name': r})
        for s in settlements:
            settlement = ET.SubElement(region, 'settlement', {'name': s})


import xml.dom.minidom # just to pretty print for this example
print(xml.dom.minidom.parseString(ET.tostring(root)).toprettyxml())

<?xml version="1.0" ?>
<data>
    <country name="Ireland">
        <region name="Cork">
            <settlement name="Cobh"/>
            <settlement name="Baltimore"/>
        </region>
        <region name="Clare">
            <settlement name="Boston"/>
        </region>
    </country>
    <country name="Sweden">
        <region name="Dalarna">
            <settlement name="Leksand"/>
            <settlement name="Mora"/>
        </region>
        <region name="Västmanland">
            <settlement name="Västerås"/>
        </region>
    </country>
</data>
于 2013-04-23T09:20:44.243 に答える