2014-02-11 2 views
5

나는 수천 개의 도시를 지오 코딩하도록 nominatim으로부터 응답을 얻으려고합니다.웹 응답에서 Xml 구문 분석

import os 
import requests 
import xml.etree.ElementTree as ET 

txt = open('input.txt', 'r').readlines() 
for line in txt: 
lp, region, district, municipality, city = line.split('\t') 
baseUrl = 'http://nominatim.openstreetmap.org/search/gb/'+region+'/'+district+'/'+municipality+'/'+city+'/?format=xml' 
# eg. http://nominatim.openstreetmap.org/search/pl/podkarpackie/stalowowolski/Bojan%C3%B3w/Zapu%C5%9Bcie/?format=xml 
resp = requests.get(baseUrl) 
resp.encoding = 'UTF-8' # special diacritics 
msg = resp.text 
# parse response to get lat & long 
tree = ET.parse(msg) 
root = tree.getroot() 
print tree 

하지만 결과는 다음과 같습니다

Traceback (most recent call last): 
File "geo_miasta.py", line 17, in <module> 
    tree = ET.parse(msg) 
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 1182, in parse 
    tree.parse(source, parser) 
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 647, in parse 
    source = open(source, "rb")  
IOError: [Errno 2] No such file or directory: u'<?xml version="1.0" encoding="UTF-8" ?>\n<searchresults timestamp=\'Tue, 11 Feb 14 21:13:50 +0000\' attribution=\'Data \xa9 OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright\' querystring=\'\u015awierczyna, Drzewica, opoczy\u0144ski, \u0142\xf3dzkie, gb\' polygon=\'false\' more_url=\'http://nominatim.openstreetmap.org/search?format=xml&amp;exclude_place_ids=&amp;q=%C5%9Awierczyna%2C+Drzewica%2C+opoczy%C5%84ski%2C+%C5%82%C3%B3dzkie%2C+gb\'>\n</searchresults>' 

이 어떤 문제가 있습니까?

편집 : 탄트 내 솔루션을 @ 롭 할 수있다 : 당신은 파일 이름이나 인수로 파일 오브젝트를 xml.etree.ElementTree.parse()를 사용하는

#! /usr/bin/env python2.7 
# -*- coding: utf-8 -*- 

import os 
import requests 
import xml.etree.ElementTree as ET 

txt = open('input.txt', 'r').read().split('\n') 

for line in txt: 
    lp, region, district, municipality, city = line.split('\t') 
    baseUrl = 'http://nominatim.openstreetmap.org/search/pl/'+region+'/'+district+'/'+municipality+'/'+city+'/?format=xml' 
    resp = requests.get(baseUrl) 
    msg = resp.content 
    tree = ET.fromstring(msg) 
    for place in tree.findall('place'): 
    location = '{:5f}\t{:5f}'.format(
     float(place.get('lat')), 
     float(place.get('lon'))) 

    f = open('result.txt', 'a') 
    f.write(location+'\t'+region+'\t'+district+'\t'+municipality+'\t'+city) 
    f.close() 

답변

6

. 그러나 파일이나 파일 객체를 전달하지 않고 유니 코드 문자열을 전달합니다.

시도 xml.etree.ElementTree.fromstring(text). 이처럼

: 여기

tree = ET.fromstring(msg) 

완전한 샘플 프로그램입니다 :

import os 
import requests 
import xml.etree.ElementTree as ET 

baseUrl = 'http://nominatim.openstreetmap.org/search/pl/podkarpackie/stalowowolski/Bojan%C3%B3w/Zapu%C5%9Bcie\n/?format=xml' 
resp = requests.get(baseUrl) 
msg = resp.content 
tree = ET.fromstring(msg) 
for place in tree.findall('place'): 
    print u'{:s}: {:+.2f}, {:+.2f}'.format(
    place.get('display_name'), 
    float(place.get('lon')), 
    float(place.get('lat'))).encode('utf-8') 
+0

감사합니다,이 인코딩 공간에 오류 국경을 이동 : 'UnicodeEncodeError을'아스키 '코덱을 할 수 있습니다' t는 문자 'ua \ xa9'를 115 번 위치로 인코딩한다. 서수는 범위 (128)가 아니다. – m93

+0

@ m93 - 이는 'resp.content' 대신에'resp.text'를 사용하기 때문이다. 내가 시작해야 할 완벽한 프로그램을 보려면 편집을 참조하십시오. –

+0

당신은 맞습니다. 이 샘플은 작동합니다. 감사. – m93

0
import os,sys,time 
import xml.etree.ElementTree as ET 
from xml.etree.ElementTree import parse 
tree = ET.parse('D:\Reddy\BankLoanAcctService_transactionInq.xml') 
root=tree.getroot() 

for TrxnEffDt in root.iter('TrxnEffDt'): 
new_TrxnEffDt= str(time.strftime("%y-%m-%d")) 
TrxnEffDt=str(new_TrxnEffDt) 

filename2 ="D:\Reddy\BankLoanAcctService_transactionInq2.txt" 
r=open(filename2,'w') 
sys.stdout =r 
+0

역 추적 (마지막으로 가장 최근 통화) : 파일 "D : \ 레디 \ 파이썬 \ new.py" 트리, 라인 4 = ET.parse ('D : \ 레디 \ BankLoanAcctService_transactionInq.xml') 파일 " C : \ Python33 \ lib \ xml \ etree \ ElementTree.py "파일, tree.parse (소스, 구문 분석기) "C : \ Python33 \ lib \ xml \ etree \ ElementTree.py " 1730, 구문 분석 self._root = parser._parse (소스) 파일 ""선 없음 xml.etree.ElementTree.ParseError에서 : 구문 오류 : 줄 1, 열 0 – user5493252

+0

이 내가 무엇입니까 오류 메시지입니다. pls help – user5493252

+0

혼란을 피하고 특정 문제에 대한 해결책을 얻으려면이 항목에 대한 대답을 사용하는 대신 직접 질문해야합니다. 문제가 관련 있다고 생각되면 응답자를 도울 수있는이 링크. – Tiesselune