首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >将Python脚本重构为可隔离的方法

将Python脚本重构为可隔离的方法
EN

Stack Overflow用户
提问于 2016-12-02 01:47:08
回答 1查看 21关注 0票数 0

有没有可能重构这个脚本,使其作为一个完全独立的方法存在?

代码语言:javascript
复制
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()

我一直在尝试让它成为一个更大的流程的组成部分。

EN

回答 1

Stack Overflow用户

发布于 2016-12-02 01:59:24

你可以做几件事。您可能希望将脚本的每个步骤分解为单独的方法,每个方法都有自己的异常处理和日志记录,以指示作业失败的位置。另外,我在这里没有提到返回参数。您可以返回True/False来提示处理是否通过/失败。

然后,您可以在其他地方导入process_file方法,并将它需要处理的两个文件传递给它。

代码语言:javascript
复制
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)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40917164

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档