用python语言写一个城市天气信息管理系统
时间: 2023-08-14 12:06:01 浏览: 84
好的,以下是一个简单的城市天气信息管理系统的Python代码:
```python
import json
class CityWeather:
def __init__(self):
self.city_weather = {}
def load_data(self):
with open('weather.json', 'r') as f:
self.city_weather = json.load(f)
def save_data(self):
with open('weather.json', 'w') as f:
json.dump(self.city_weather, f)
def add_city(self, city, weather):
if city in self.city_weather:
print("该城市已存在!")
else:
self.city_weather[city] = weather
print("添加成功!")
def delete_city(self, city):
if city not in self.city_weather:
print("该城市不存在!")
else:
del self.city_weather[city]
print("删除成功!")
def update_city(self, city, weather):
if city not in self.city_weather:
print("该城市不存在!")
else:
self.city_weather[city] = weather
print("更新成功!")
def search_city(self, city):
if city not in self.city_weather:
print("该城市不存在!")
else:
print(f"{city}的天气为:{self.city_weather[city]}")
def show_all_cities(self):
for city in self.city_weather:
print(city)
if __name__ == '__main__':
cw = CityWeather()
cw.load_data()
while True:
print("请选择操作:1.添加城市 2.删除城市 3.更新城市 4.查询城市 5.显示所有城市 6.退出")
choice = input()
if choice == '1':
city = input("请输入城市名:")
weather = input("请输入天气情况:")
cw.add_city(city, weather)
cw.save_data()
elif choice == '2':
city = input("请输入要删除的城市名:")
cw.delete_city(city)
cw.save_data()
elif choice == '3':
city = input("请输入要更新的城市名:")
weather = input("请输入新的天气情况:")
cw.update_city(city, weather)
cw.save_data()
elif choice == '4':
city = input("请输入要查询的城市名:")
cw.search_city(city)
elif choice == '5':
cw.show_all_cities()
elif choice == '6':
break
else:
print("输入有误,请重新输入!")
```
该系统使用了一个字典来存储城市天气信息,并且将数据保存在一个JSON文件中。用户可以选择添加、删除、更新、查询、显示城市信息。用户的选择会对应不同的操作,例如添加城市、删除城市等。程序中也提供了对输入错误的处理,保证程序的稳定性。
阅读全文