2016-12-01 4 views
0

Ist es möglich, dieses Skript so umzuformen, dass es als völlig unabhängige Methode existiert?Python-Skript in eine isolierbare Methode umwandeln

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() 

Ich habe versucht, es so zu machen, dass ich es als eine Komponente eines viel größeren Prozesses einschließen kann.

Antwort

2

Es gibt ein paar Dinge, die Sie tun können. Möglicherweise möchten Sie jeden Schritt des Skripts in separate Methoden aufteilen, die jeweils eine eigene Ausnahmebehandlung enthalten, und eine Protokollierung durchführen, um anzugeben, wo der Job fehlgeschlagen ist. Außerdem habe ich den Rückgabeparameter hier nicht erwähnt. Sie können ein Richtiges/Falsches zurückgeben, um vorzuschlagen, ob die Verarbeitung bestanden/fehlgeschlagen ist.

Sie können die process_file-Methode dann an anderen Stellen importieren und ihr die 2 Dateien übergeben, die sie verarbeiten muss.

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

Ich versuche, es zu übernehmen schließlich in [dieses Ding] (http://stackoverflow.com/questions/40914419/parse-json-from-an-api-with-python-exception-handling- chirurgische Extraktion) –

Verwandte Themen