0

我有一个递归脚本,它正在为汽车抓取 JSON 文件。在每个递归级别,它都会添加一个新变量,并将其(与其他值一起)传递给递归调用,每次都会获得越来越详细的信息。我尝试使用locals()动态分配一个变量,但None即使在调用之后它仍然存在(我记得有时看到它locals()是只读的)。

我也尝试过使用eval(),它给了我同样的问题(我知道 eval 并不理想)。理想情况下,我希望避免使用字典,因为这需要我先用值加载它,这似乎有一些不必要的步骤,但我现在对任何事情都持开放态度。

例子:

scraper(manufacturer='Honda')将抓取模型的 JSON 文件,设置model='Accord'然后递归调用

scraper(manufacturer='Honda, model='Accord')它会刮掉一个年份的文件,设置year=2014并递归调用

scraper(manufacturer='Honda', model='Accord', year='2014')这是基本情况

def scraper(self, manufacturers, model=None, year=None):

    if year:
        scrapeurl = '%s&manufacturer=%s&model=%s&year=%s' % (url, manufacturer, model, year)
        return someFinalFunction()

    elif model:
        scrapeurl = '%s&manufacturer=%s&model=%s' % (url, manufacturer, model)

    elif manufacturer:
        scrapeurl = '%s&manufacturer=%s' % (url, manufacturer)

    j = getJSONFromUrl(scrapeurl)
    key, values = j.popitems()

    for value in values:
        locals()[key] = value
        return self.scraper(manufacturer, model, year, color)

我会很感激有关如何处理这个问题的任何意见,我知道 Python 似乎总是有一些聪明的做事方式,而且我一直在学习更多关于它的知识,所以提前谢谢你!我也在这个例子中使用 Python3,如果这改变了什么

4

2 回答 2

2

locals()['key'] = value应该locals()[key] = value


更好的是,使用**kwargs

def scraper(self, manufacturer, model=None, year=None):
    kwargs = dict(manufacturer=manufacturer, model=model, year=year)

    if year:
        scrapeurl = '%s&manufacturer=%s&model=%s&year=%s' % (url, manufacturer, model, year)
        return someFinalFunction()

    elif model:
        scrapeurl = '%s&manufacturer=%s&model=%s' % (url, manufacturer, model)

    elif manufacturer:
        scrapeurl = '%s&manufacturer=%s' % (url, manufacturer)

    j = getJSONFromUrl(scrapeurl)
    key, values = j.popitems()

    for value in values:
        kwargs[key] = value
        return self.scraper(**kwargs)
于 2014-10-19T18:03:46.223 回答
1

目前尚不清楚您要做什么,但也许这会有所帮助:

def scraper(self, **kwargs):

    if kwargs.get('year') is not None:
        scrapeurl = '{0}&manufacturer={manufacturer}&model={model}&year={year}'
        return someFinalFunction() # not sure why this takes no arguments

    elif kwargs.get('model') is not None:
        scrapeurl = '{0}&manufacturer={manufacturer}&model={model}'

    elif kwargs.get('manufacturer') is not None:
        scrapeurl = '{0}&manufacturer={manufacturer}'

    else:
        raise KeyError

    j = getJSONFromUrl(scrapeurl.format(url, **kwargs))
    key, values = j.popitems()

    for value in values:
        kwargs[key] = value
        return self.scraper(**kwargs)

这使用 Python 的内置功能将任意关键字参数视为字典,以及更现代的str.format字符串格式,以动态处理您正在寻找的参数。唯一的区别是您现在需要调用它:

instance.scraper(manufacturer='...')

而不仅仅是

instance.scraper('...')

字符串格式化、混合位置参数和关键字参数的示例:

>>> '{0}&manufacturer={manufacturer}'.format('foo', **{'manufacturer': 'bar'})
'foo&manufacturer=bar'
于 2014-10-19T18:09:58.137 回答