
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
다음 명령을 사용하여 두 가지를 결합할 수 있습니다.
./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)