将 for index, adcode_dict in enumerate(adcode_list, 1): # 获取adcode 用于拼接完整的url adcode = adcode_dict["adcode"] # 拼接完整的url full_url = base_url + adcode # 发送请求获取天气json数据 response = requests.get(full_url) json_data = response.json() # 第一种方式 # msg = json_data.get("data").get("message") # if msg == "Successful.": # # 获取天气信息 # weather_name = json_data.get("data").get("data")[0].get("live").get("weather_name") # # print(weather_name) # # # 将天气信息 加入到adcode_dict中 # adcode_dict["weather_name"] = weather_name # print(c, adcode_dict) # else: # print(msg) # 第二种方式 try: # 获取天气信息 weather_name = json_data.get("data").get("data")[0].get("live").get("weather_name") # 将天气信息加入到adcode_dict中 adcode_dict["weather_name"] = weather_name if weather_name == '晴': sunny += 1 elif weather_name == '多云': cloud += 1 elif weather_name == '阴': being_cloud += 1 elif '雨' in weather_name: rain += 1 else: haze += 1 print(index, adcode_dict) except Exception as e: print(e)变成一个生成器函数
时间: 2024-02-10 09:30:17 浏览: 35
可以将上述代码改写成生成器函数,每次yield返回一个包含天气信息的adcode_dict字典,例如:
```python
import requests
def get_weather_info(adcode_list):
base_url = "http://www.weather.com.cn/data/cityinfo/"
sunny = cloud = being_cloud = rain = haze = 0
for index, adcode_dict in enumerate(adcode_list, 1):
adcode = adcode_dict["adcode"]
full_url = base_url + adcode
response = requests.get(full_url)
json_data = response.json()
try:
weather_name = json_data.get("weatherinfo").get("weather")
adcode_dict["weather_name"] = weather_name
yield adcode_dict
if weather_name == '晴':
sunny += 1
elif weather_name == '多云':
cloud += 1
elif weather_name == '阴':
being_cloud += 1
elif '雨' in weather_name:
rain += 1
else:
haze += 1
except Exception as e:
print(e)
print("晴天数量:", sunny)
print("多云数量:", cloud)
print("阴天数量:", being_cloud)
print("雨天数量:", rain)
print("雾霾天数量:", haze)
```
调用该生成器函数可以使用for循环来遍历生成器对象,例如:
```python
adcode_list = [{"adcode": "101010100", "city": "北京"},
{"adcode": "101020100", "city": "上海"},
{"adcode": "101280101", "city": "广州"},
{"adcode": "101280601", "city": "深圳"}]
for adcode_dict in get_weather_info(adcode_list):
print(adcode_dict)
```
这将输出每个城市对应的天气信息,并统计不同天气类型的数量。