XML形式のPython出力

XML形式のPython出力

IPリストをIPデータベースと比較し、基準に一致する出力を提供するPythonスクリプトがあります。 (このフォーラムからスクリプトを取得しました)。

変換.py

    #!/usr/bin/python
    import socket,struct
    db=[]
    for l in open("database.txt"):
        fields=l.split();
        db.append((int(fields[0]),int(fields[1]),fields[-2],fields[-1]))

    for l in open("iplist.txt"):
        ip=struct.unpack('!I',socket.inet_aton(l))[0]
        for e in db:
            if e[0]<=ip<=e[1]:
                print l.strip(),e[2],e[3]
                break

出力はcsv形式で、XML形式で出力したいです。 AWKコマンドを使用してこれを達成します。

awk -F" " 'BEGIN{print"<markers>"} {printf"<marker information=\"%s\" Longitude=\"%s\" Latitude=\"%s\" />\n",$1,$3,$2} END{print"</markers>"}' mapinfo.csv

次のコマンドを使用して2つを組み合わせることができます。

./convert.py | awk -F" " 'BEGIN{print"<markers>"} {printf"<marker information=\"%s\" Longitude=\"%s\" Latitude=\"%s\" />\n",$1,$3,$2} END{print"</markers>"}'

Pythonスクリプト自体内でawkを使用する方法、または目的の形式で表示する他の方法についてのヘルプが必要ですか?

出力:

<markers>
<marker information="168.144.247.215" Longitude="-79.377040" Latitude="43.641233" />
<marker information="169.255.59.2" Longitude="28.043630" Latitude="-26.202270" />
<marker information="173.230.253.193" Longitude="-83.227531" Latitude="42.461234" />
<marker information="173.247.245.154" Longitude="-118.343030" Latitude="34.091104" />
<marker information="174.142.197.90" Longitude="-73.587810" Latitude="45.508840" />
<marker information="175.107.192.78" Longitude="67.082200" Latitude="24.905600" />
</markers>

ベストアンサー1

この例では、すべてのcsvコンテンツがa.csvというファイルにあると想定しています。stdout stream代わりにそれを使用するように変更できます。file stream

怠惰なので、経度、緯度を子要素にしました。プロパティにすることもできます。

 from xml.etree.ElementTree import Element, SubElement, Comment, tostring

top = Element('markers')
f = open('a.csv')
for line in f:
  split_list = line.strip().split(',')
  information_txt = split_list[0]
  longitude_txt = split_list[1]
  latitude_txt = split_list[2]
  marker = SubElement(top, 'marker')
  info = SubElement(marker, 'information')
  info.text = information_txt
  longitude = SubElement(marker, 'longitude')
  longitude.text = longitude_txt
  latitude = SubElement(marker, 'latitude')
  latitude.text = latitude_txt

print tostring(top)

おすすめ記事