1

我想知道在 Python 中是否有更有效的方法来做到这一点。我在 Ruby 中找到了一个很好的解决方案,但它似乎相当具体。

基本上,我从一个 API 获取天气状况数据,并希望将它们的许多细微差别的条件标准化到七个我可以轻松处理的情况。

def standardize_weather_conditions(s):
    clear_chars = ['clear', 'sunny']
    clouds_chars = ['cloudy', 'overcast', 'fog']
    storm_chars = ['thunder']
    freezing_chars = ['ice', 'sleet', 'freezing rain', 'freezing drizzle']
    snow_chars = ['snow', 'blizzard']
    rain_chars = ['rain', 'drizzle', 'mist']

    if any_in_string(s, clear_chars):
        conditions = 'clear'
    elif any_in_string(s, clouds_chars):
        conditions = 'clouds'
    elif any_in_string(s, storm_chars):
        conditions = 'storm'
    elif any_in_string(s, freezing_chars):
        conditions = 'freezing'
    elif any_in_string(s, snow_chars):
        conditions = 'snow'
    elif any_in_string(s, wet_chars):
        conditions = 'wet'
    else:
        conditions = 'other'
    return conditions

def any_in_string(s, array):
    for e in array:
        if e in s:
            return True
    return False
4

2 回答 2

2

any_in_string可以通过做单线return any([x in s for x in array])

然后,您可以制作一个字典,将您的描述映射到您的搜索词列表:

all_chars = {'clear':clear_chars, \
             'clouds':clouds_chars, \
             'storm':storm_chars, \
             'freezing':freezing_chars, \
             'snow':snow_chars, \
             'wet':rain_chars }

for key in all_chars.keys():
     if any_in_string(s, all_chars[keys]):
         return key

return 'other'

这将有助于避免您拥有的“意大利面条代码”if-else 块。

如果您想更花哨,可以将for上面的循环更改为:

conditions = [x for x in all_chars.keys() if any_in_string(s, all_chars[x])]
conditions = ' and '.join(conditions)
return conditions

这样你就可以得到类似的东西cloudy and wet

于 2012-12-06T02:22:22.630 回答
2

You can define like this:

def any_in_string(s, lst):
    return any(word in s for word in lst)
于 2012-12-06T02:18:51.477 回答