0

I have a python script which compare IP list with IP Database and gives output of matching criteria. (I got the script from this forum).

convert.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

The output is in csv format and I want the output in XML, I'm achieving this using AWK command,

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

I can use the following command to combine both,

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

Any help on how can I use the awk within the python script itself or any other way to display in required format?

Output:

<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>
2

This example assumes, all the csv contents are lying in a file named a.csv...you can change it to use stdout stream instead of file stream

and out of laziness, i put longitude, latitude as sub-elements.. you can put them as attributes as well

 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)
  • corrected an error... – Madhavan Jul 2 '15 at 10:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.