我想知道在 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