2016-12-01 3 views
0

이 스크립트를 완전히 독립적 인 방법으로 리팩토링 할 수 있습니까?리팩토링 파이썬 스크립트를 분리 가능한 방법으로

import json 
import requests 
from collections import defaultdict 
from pprint import pprint 

def hasNumbers(inputString): 
    return any(char.isdigit() for char in inputString) 

# open up the output of 'data-processing.py' 
with open('job-numbers-by-location.txt') as data_file: 

    # print the output to a file 
    with open('phase_ii_output.txt', 'w') as output_file_: 
     for line in data_file: 
      identifier, name, coords, number_of_jobs = line.split("|") 
      coords = coords[1:-1] 
      lat, lng = coords.split(",") 
      # print("lat: " + lat, "lng: " + lng) 
      response = requests.get("http://api.geonames.org/countrySubdivisionJSON?lat="+lat+"&lng="+lng+"&username=s.matthew.english").json() 


      codes = response.get('codes', []) 
      for code in codes: 
       if code.get('type') == 'ISO3166-2': 
        country_code = '{}-{}'.format(response.get('countryCode', 'UNKNOWN'), code.get('code', 'UNKNOWN')) 
        if not hasNumbers(country_code): 
         # print("code: " + country_code + ", jobs: " + number_of_jobs) 
         output_file_.write("code: " + country_code + ", jobs: " + number_of_jobs) 
    output_file_.close() 

나는 그것을 훨씬 더 큰 프로세스의 구성 요소로 포함시킬 수 있도록 노력해 왔습니다.

답변

2

몇 가지 작업을 수행 할 수 있습니다. 스크립트의 각 단계를 자체적 인 예외 처리를 사용하는 별도의 메소드로 분리하고 작업이 실패한 위치를 나타내는 로깅을 원할 수 있습니다. 또한 여기서 return 매개 변수는 언급하지 않았습니다. True/False를 반환하여 처리가 성공/실패했는지 여부를 제안 할 수 있습니다.

그러면 다른 위치에서 process_file 메소드를 가져 와서 처리해야하는 2 개의 파일을 전달할 수 있습니다.

import json 
import requests 
from collections import defaultdict 
from pprint import pprint 

def hasNumbers(inputString): 
    return any(char.isdigit() for char in inputString) 

def handle_get(url, params) 
    try: 
     response = requests.get(url, params=urlencode(params)) 
    except requests.exceptions.RequestException as e: # This is the correct syntax 
     print e 
     # sys.exit(1) 
     response = None 

    return response 

def process_file(data_file_path, output_file_path) 
    # open up the output of 'data-processing.py' 
    with open(data_file_path) as data_file: 

     # print the output to a file 
     with open(output_file_path, 'w') as output_file_: 
      for line in data_file: 
       identifier, name, coords, number_of_jobs = line.split("|") 
       coords = coords[1:-1] 
       lat, lng = coords.split(",") 
       params = OrderedDict([('lat', lat), ('lng', lng), ('username', 's.matthew.english')]) 
       url = "http://api.geonames.org/countrySubdivisionJSON" 
       response = handle_get(url, params) 
       if response: 
        json_response = response.json() 
       else: 
        print('Something bad happened') 
        sys.exit(1) 


       codes = response.get('codes', []) 
       for code in codes: 
        if code.get('type') == 'ISO3166-2': 
         country_code = '{}-{}'.format(response.get('countryCode', 'UNKNOWN'), code.get('code', 'UNKNOWN')) 
         if not hasNumbers(country_code): 
          # print("code: " + country_code + ", jobs: " + number_of_jobs) 
          output_file_.write("code: " + country_code + ", jobs: " + number_of_jobs) 
+0

나는 결국 [이 일] (http://stackoverflow.com/questions/40914419/parse-json-from-an-api-with-python-exception-handling-에 통합하기 위해 노력하고있어 외과 적 추출) –