2017-02-07 5 views
1

다음 작업을 수행하는 Python 스크립트를 작성해야합니다. 하나의 목록에 300 개의 도시가있는 xlsx/csv 파일이 있습니다. 열파이썬에서 가능한 모든 조합을 만들고 csv/xlsx 파일 용 google API도 사용합니다.

  1. 나는 그들 사이에이 모양

CSV 파일는 내가 두 번째 열에서의 거리 및 여행 시간을 추가 할 필요가 구글 API의 도움으로 모든 쌍을해야 :

이 작업을 수행하는 방법을
======= 
SOURCE 
======= 
Agra 
Delhi 
Jaipur 

및 CSV/XLSX 파일에서 출력 등등이

============================================= 
SOURCE | DESTINATION | DISTANCE | TIME_TRAVEL 
============================================= 
Agra | Delhi | 247 |  4  
Agra | Jaipur | 238 |  4  
Delhi | Agra  | 247 |  4  
Delhi | jaipur | 281 |  5 
Jaipur | Agra  | 238 |  4  
Jaipur | Delhi | 281 |  5   

및처럼 예상 ....?
참고 : 거리 및 이동 시간은 Google입니다.

+0

파일에서 도시가 3 행째부터 시작합니까? – MYGz

+0

제목을 삭제할 수 있습니다. 그리고 스크립트를 실행 한 후 제목을 추가 할 수 있습니다. 단 하나의 라인입니다. 그것이 더 명확 할 것이기 때문에 문제가됩니다. 도시가 위로부터 시작합니다 –

+0

문제는 테스트 할 수 없으므로 최선을 다할 수 있습니다. – MYGz

답변

1

쌍을 만들려면 itertools.permutations를 사용하여 가능한 모든 쌍을 얻을 수 있습니다. 같은 대한 코드는 것 같은 : 그 전체 디버깅을 위해 작동 할 수이 샘플 코드 구글에서 거리와 시간의 취득 외에도

import csv  # imports the csv module 
import sys  # imports the sys module 
import ast 
import itertools  
source_list = [] 
destination_list = [] 
type_list = []list 
f = open(sys.argv[1], 'rb') 
g = open(sys.argv[2], 'wb') 
# opens the csv file 
try: 
    reader = csv.reader(f) 
    my_list = list(reader) # creates the reader object 
    for i in my_list: 
     source_list.append(i[0]) 
    a = list(itertools.permutations(source_list, 2)) 
    for i in a: 
     source_list.append(i[0]) 
     destination_list.append(i[1]) 
    mywriter=csv.writer(g) 
    rows = zip(source_list,destination_list) 
    mywriter.writerows(rows) 
    g.close() 

finally: 
    f.close() 

.

import csv  # imports the csv module 
import sys  # imports the sys module 
import urllib2,json 
import ast 
api_google_key = '' 
api_google_url = 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=' 
source_list = [] 
destination_list = [] 
distance_list = [] 
duration_list = [] 
f = open(sys.argv[1], 'rb') 
g = open(sys.argv[2], 'wb') 
# opens the csv file 
try: 
    reader = csv.reader(f) 
    my_list = list(reader) # creates the reader object 
    for i in my_list: 
    if i: 
      s = (i[0]) 
     src = s.replace(" ","") 
      d = (i[1]) 
     dest = d.replace(" ","") 
     source = ''.join(e for e in src if e.isalnum()) 
     destination = ''.join(e for e in dest if e.isalnum()) 
     print 'source status = '+str(source.isalnum()) 
     print 'dest status = '+str(destination.isalnum()) 
     source_list.append(source) 
      destination_list.append(destination) 
      request = api_google_url+source+'&destinations='+destination+'&key='+api_google_key 
     print request 
      dist = json.load(urllib2.urlopen(request)) 
     if dist['rows']: 
       if 'duration' in dist['rows'][0]['elements'][0].keys(): 
         duration_dict = dist['rows'][0]['elements'][0]['duration']['text'] 
         distance_dict = dist['rows'][0]['elements'][0]['distance']['text'] 
       else: 
        duration_dict = 0 
        distance_dict = 0 
     else: 
       duration_dict = 0 
       distance_dict = 0 

      distance_list.append(distance_dict) 
      duration_list.append(duration_dict) 
    mywriter=csv.writer(g) 
    rows = zip(source_list,destination_list,distance_list,duration_list) 
    mywriter.writerows(rows) 
    g.close() 

finally: 
    f.close() 
+0

고마워. 그것은 작동합니다. :) –

0

당신과 같이 itertools.permutations() 모든 조합을 얻을 수 있습니다 : 그런 다음 1 목록 요소를 하나의 API를 칠 수

from itertools import permutations 

with open(cities_file, 'r') as f, open(newfile, 'w') as f2: 
    for pair in (permutations([a.strip() for a in f.read().splitlines()], 2)): 
     print pair 
     response = googleapi.get(pair) 
     f2.write(response+'\n') 

출력

('Agra', 'Delhi') 
('Agra', 'Jaipur') 
('Delhi', 'Agra') 
('Delhi', 'Jaipur') 
('Jaipur', 'Agra') 
('Jaipur', 'Delhi') 

print pair의하고 결과를 저장 보관 파일에.

+0

감사합니다. :) –

+0

당신의 노력에 감사드립니다. :) –

0

itertools.product을 사용하면이 작업을 수행 할 수 있습니다.하지만 이는 실제로 거리가 0이 될 (Agra, Agra)과 같은 반복을 얻게됨을 의미합니다.

이 경우
import itertools 
cities = ["Agra","Delhi","Jaipur"] 
cities2 = cities 
p = itertools.product(cities, cities2) 
print(list(p)) 

당신은

[('Agra', 'Agra'), ('Agra', 'Delhi'), ('Agra', 'Jaipur'), ('Delhi', 'Agra'), ('Delhi', 'Delhi'), ('Delhi', 'Jaipur'), ('Jaipur', 'Agra'), ('Jaipur', 'Delhi'), ('Jaipur', 'Jaipur')] 

당신은 이동 시간과 거리를 얻기 위해 Google에 요청을이 forlist에서 루프를 가지고 만들 수 있습니다 얻을 것입니다.

>>> for pair in list(p): 
...  print (pair) 
... 
('Agra', 'Agra') 
('Agra', 'Delhi') 
('Agra', 'Jaipur') 
('Delhi', 'Agra') 
('Delhi', 'Delhi') 
('Delhi', 'Jaipur') 
('Jaipur', 'Agra') 
('Jaipur', 'Delhi') 
('Jaipur', 'Jaipur') 
+0

당신의 노력에 감사드립니다. :) –